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

相关推荐
胖咕噜的稞达鸭1 小时前
数据结构---关于复杂度的基础解析与梳理
c语言·数据结构·算法·leetcode
高山莫衣1 小时前
Polyak-Ruppert 平均
人工智能·算法·机器学习
秋难降3 小时前
【数据结构与算法】———链表归并排序的优势
python·算法·排序算法
用户30356298445743 小时前
LightRAG应用实践
人工智能·算法
用户49430538293803 小时前
大规模建筑自动贴图+单体化效果,cesium脚本
前端·javascript·算法
minji...5 小时前
算法题Day1
c++·算法
weixin_307779135 小时前
GCC C++实现Matlab矩阵计算和数学函数功能
c++·算法
东方佑6 小时前
UniVoc:基于二维矩阵映射的多语言词汇表系统
人工智能·算法·矩阵
汤永红6 小时前
week1-[分支结构]中位数
c++·算法·信睡奥赛
啊阿狸不会拉杆6 小时前
《算法导论》第 24 章 - 单源最短路径
开发语言·数据结构·c++·算法·php