[力扣题解] 463. 岛屿的周长

题目:463. 岛屿的周长

思路

深度优先搜索;

代码

Method 1

对于遍历到的一个地块,向四周探索,越界或者遇到海洋地块说明这条边需要统计;

cpp 复制代码
class Solution {
private:
    int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    int result = 0; // 周长
    void dfs(vector<vector<int>>& grid, vector<vector<bool>>& vistied, int x, int y)
    {
        int m = grid.size(), n = grid[0].size();
        int i, j;
        int next_x, next_y;

        for(i = 0; i < 4; i++)
        {
            next_x = x + dir[i][0];
            next_y = y + dir[i][1];
            if(next_x < 0 || next_x >= m || next_y < 0 || next_y >= n)
            {
                result++;
                continue;
            }
            if(grid[next_x][next_y] == 0)
            {
                result++;
            }
            if(!vistied[next_x][next_y] && grid[next_x][next_y] == 1)
            {
                vistied[next_x][next_y] = true;
                dfs(grid, vistied, next_x, next_y);
            }
        }
    }

public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        int i, j;
        vector<vector<bool>> vistied(m, vector<bool>(n, false));

        for(i = 0; i < m; i++)
        {
            for(j = 0; j < n; j++)
            {
                if(!vistied[i][j] && grid[i][j] == 1)
                {
                    vistied[i][j] = true;
                    dfs(grid, vistied, i, j);
                }
            }
        }
        return result;
    }
};

Method 2

初始周长 = 岛屿地块 * 4,在岛屿内部,有一对相邻地块,周长-2

相关推荐
czy87874754 分钟前
两种常见的C语言实现64位无符号整数乘以64位无符号整数的实现方法
c语言·算法
yzx99101320 分钟前
支持向量机案例
算法·机器学习·支持向量机
天上路人31 分钟前
采用AI神经网络降噪算法的语言降噪消回音处理芯片NR2049-P
深度学习·神经网络·算法·硬件架构·音视频·实时音视频·可用性测试
chao_78944 分钟前
手撕算法(定制整理版2)
笔记·算法
AndrewHZ3 小时前
【图像处理基石】什么是油画感?
图像处理·人工智能·算法·图像压缩·视频处理·超分辨率·去噪算法
.格子衫.3 小时前
015枚举之滑动窗口——算法备赛
数据结构·算法
J先生x4 小时前
【IP101】图像处理进阶:从直方图均衡化到伽马变换,全面掌握图像增强技术
图像处理·人工智能·学习·算法·计算机视觉
爱coding的橙子6 小时前
每日算法刷题 Day3 5.11:leetcode数组2道题,用时1h(有点慢)
算法·leetcode
Dream it possible!10 小时前
LeetCode 热题 100_只出现一次的数字(96_136_简单_C++)(哈希表;哈希集合;排序+遍历;位运算)
c++·leetcode·位运算·哈希表·哈希集合
?abc!11 小时前
缓存(5):常见 缓存数据淘汰算法/缓存清空策略
java·算法·缓存