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

相关推荐
Once_day9 分钟前
代码训练LeetCode(46)旋转图像
算法·leetcode·职场和发展
悠哉清闲17 分钟前
C++ 指针与引用
java·c++·算法
然我43 分钟前
链表指针玩不转?从基础到双指针,JS 实战带你破局
前端·数据结构·算法
EndingCoder1 小时前
算法与前端的可访问性
前端·算法·递归·树形结构
ysa0510301 小时前
竞赛常用加速技巧#模板
c++·笔记·算法
7 971 小时前
C语言基础知识--文件的顺序读写与随机读写
java·数据结构·算法
2401_841003981 小时前
Kubernetes 资源管理全解析
算法·贪心算法
☆璇2 小时前
【数据结构】排序
c语言·开发语言·数据结构·算法·排序算法
艾莉丝努力练剑5 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途7 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法