[力扣题解] 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

相关推荐
夏鹏今天学习了吗4 小时前
【LeetCode热题100(82/100)】单词拆分
算法·leetcode·职场和发展
mit6.8245 小时前
mysql exe
算法
2501_901147836 小时前
动态规划在整除子集问题中的应用与高性能实现分析
算法·职场和发展·动态规划
中草药z6 小时前
【嵌入模型】概念、应用与两大 AI 开源社区(Hugging Face / 魔塔)
人工智能·算法·机器学习·数据集·向量·嵌入模型
踩坑记录6 小时前
leetcode hot100 189.轮转数组 medium
leetcode
知乎的哥廷根数学学派6 小时前
基于数据驱动的自适应正交小波基优化算法(Python)
开发语言·网络·人工智能·pytorch·python·深度学习·算法
ADI_OP7 小时前
ADAU1452的开发教程10:逻辑算法模块
算法·adi dsp中文资料·adi dsp·adi音频dsp·adi dsp开发教程·sigmadsp的开发详解
xingzhemengyou17 小时前
C语言 查找一个字符在字符串中第i次出现的位置
c语言·算法
Dream it possible!7 小时前
LeetCode 面试经典 150_二分查找_在排序数组中查找元素的第一个和最后一个位置(115_34_C++_中等)
c++·leetcode·面试
小六子成长记9 小时前
【C++】:搜索二叉树的模拟实现
数据结构·c++·算法