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

相关推荐
CAD开发小慧4 分钟前
CAE软件开发:Coreform为何用ACIS处理CAD几何?
算法·架构·计算机图形学
七牛云行业应用8 分钟前
DeepSeek Harness 自定义 Skill 教程:从 SKILL.md 到可复用 Agent 工作流
算法·github
hetao173383712 分钟前
2026-10-14 hetao1733837 的刷题记录
c++·算法
罗斯83926 分钟前
Datalog与安全分析
算法·安全·网络安全
浅念-1 小时前
动态规划:线性DP——多状态DP与子数组专题笔记
c++·笔记·算法·leetcode·职场和发展·动态规划·力扣
Data analyse4561 小时前
rrweb回放事件资源加载顺序重放校验
前端·人工智能·算法·机器学习·数据分析
昨夜见军贴06161 小时前
原始采样记录数字化落地,IACheck AI 报告文档审核 Agent 实现监测文档校验自动化
人工智能·算法·自动化
微学AI2 小时前
从历史曲线到提前预警:TimechoAI 的时序预测与业务落地实践
人工智能·算法
不会就选b2 小时前
算法日常・每日刷题--<动态规划>26
算法·动态规划
荆棘鸟智能2 小时前
虫情测报灯图像识别算法实践:小目标检测、粘连计数与飞虱细粒度分类
算法·目标检测·分类