[力扣题解] 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 分钟前
【数据结构-初阶】详解线性表(2)---单链表
c语言·数据结构·算法
牛三金2 分钟前
魔改-隐语PSI通信,支持外部通信自定义
服务器·前端·算法
菜鸟233号2 分钟前
力扣106 从中序与后序遍历序列构造二叉树 java实现
java·算法·leetcode
Donald_wsn6 分钟前
牛客 栈和排序 C++
数据结构·c++·算法
沃达德软件9 分钟前
智慧警务实战模型与算法
大数据·人工智能·算法·数据挖掘·数据分析
LYFlied17 分钟前
LeetCode热题Top100:核心算法思想与前端实战套路
前端·算法·leetcode·面试·算法思想·算法套路·解题公式
coderxiaohan18 分钟前
【C++】红黑树的实现
数据结构·c++·算法
AganTee21 分钟前
儿童编程学什么内容?怎么学?(附3个实用工具)
算法·青少年编程·推荐算法
coderxiaohan21 分钟前
【C++】封装红黑树实现mymap和myset
数据结构·c++·算法
源来有你_27 分钟前
排序总结和练习
数据结构·算法·排序算法