当前位置: 首页> 财经> 金融 > [力扣题解] 463. 岛屿的周长

[力扣题解] 463. 岛屿的周长

时间:2025/7/11 14:21:59来源:https://blog.csdn.net/weixin_44092088/article/details/139089091 浏览次数:0次

题目:463. 岛屿的周长

思路

深度优先搜索;

代码

Method 1

对于遍历到的一个地块,向四周探索,越界或者遇到海洋地块说明这条边需要统计;

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

关键字:[力扣题解] 463. 岛屿的周长

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: