[力扣题解] 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 分钟前
计算机图形学·20 绘制(Implementation)1与Cohen-Sutherland算法
人工智能·算法·计算机视觉·计算机图形学·opengl
严文文-Chris2 分钟前
反向传播算法是什么?和神经网络的关系?
人工智能·神经网络·算法
CoderYanger2 分钟前
动态规划算法-路径问题:10.地下城游戏
开发语言·算法·leetcode·游戏·职场和发展·动态规划·1024程序员节
liu****3 分钟前
11.字符函数和字符串函数(二)
c语言·开发语言·数据结构·c++·算法
机器学习之心15 分钟前
MATLAB基于改进蜣螂优化算法的磨削参数低碳优化
算法·matlab·基于改进蜣螂优化算法·磨削参数低碳优化
IT_Octopus23 分钟前
算法题:力扣 热题100道 中等难度128. 最长连续序列
算法·leetcode
浅川.2525 分钟前
xtuoj 方程
算法
Swift社区27 分钟前
LeetCode 441 - 排列硬币
算法·leetcode·职场和发展
TL滕30 分钟前
从0开始学算法——第七天(快速排序算法练习)
笔记·学习·算法·排序算法
MicroTech202532 分钟前
MLGO微算法科技 D-S融合算法技术发布,助力脑机接口迈向实用化
大数据·科技·算法