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

相关推荐
ANYOLY14 小时前
Sentinel 限流算法详解
算法·sentinel
No0d1es15 小时前
电子学会青少年软件编程(C/C++)六级等级考试真题试卷(2025年9月)
c语言·c++·算法·青少年编程·图形化编程·六级
AndrewHZ15 小时前
【图像处理基石】图像去雾算法入门(2025年版)
图像处理·人工智能·python·算法·transformer·cv·图像去雾
Knox_Lai15 小时前
数据结构与算法学习(0)-常见数据结构和算法
c语言·数据结构·学习·算法
橘颂TA15 小时前
【剑斩OFFER】算法的暴力美学——矩阵区域和
算法·c/c++·结构与算法
不会c嘎嘎15 小时前
每日一练 -- day1
c++·算法
hansang_IR16 小时前
【记录】网络流最小割建模三题
c++·算法·网络流·最小割
xwill*16 小时前
Helix: A Vision-Language-Action Model for Generalist Humanoid Control
人工智能·算法
blammmp16 小时前
算法专题二十:贪心算法
数据结构·算法·贪心算法
Dream it possible!16 小时前
LeetCode 面试经典 150_二叉树层次遍历_二叉树的层序遍历(83_102_C++_中等)
c++·leetcode·面试·二叉树