[leetCode]463. 岛屿的周长
题目
给定一个包含 0 和 1 的二维网格地图,其中 1 表示陆地 0 表示水域。
网格中的格子水平和垂直方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。
岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。
输入:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
输出: 16
解释: 它的周长是下面图片中的 16 个黄色的边:
bfs
思路: 遍历网格,当找到值为1的格子时进行广度优先搜索,使用计数器记录当前格子边的个数,在遍历下一个格子之前将计数器的值进行累加然后重新开始计数,最后就能得到岛屿的周长。
class Solution {
public int islandPerimeter(int[][] grid) {
int[][] dirs = new int[][]{{1,0},{0,1},{-1,0},{0,-1}};
int rows = grid.length;
int cols = grid[0].length;
boolean[][] seen = new boolean[rows][cols];
Queue<int[]> queue = new LinkedList<>();
int ans = 0;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (grid[row][col] == 1) {
queue.offer(new int[]{row, col});
seen[row][col] = true;
while (!queue.isEmpty()) {
int[] cur = queue.poll();
int cnt = 0;
for (int[] dir : dirs) {
int nx = cur[0] + dir[0];
int ny = cur[1] + dir[1];
if (nx < 0 || nx >= rows || ny < 0
|| ny >= cols || grid[nx][ny] == 0) {
cnt++;
continue;
}
if (seen[nx][ny]) continue;
queue.offer(new int[]{nx, ny});
seen[nx][ny] = true;
}
ans += cnt;
}
return ans;
}
}
}
return ans;
}
}
迭代
思路: 遍历网格,如果格子值为1则对该格子的边进行计数,然后累加,最后得到岛屿的周长
class Solution {
public int islandPerimeter(int[][] grid) {
int[][] dirs = new int[][]{{1,0},{0,1},{-1,0},{0,-1}};
int rows = grid.length;
int cols = grid[0].length;
int ans = 0;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
int cnt = 0;
if (grid[row][col] == 1) {
for (int[] dir : dirs) {
int nx = row + dir[0];
int ny = col + dir[1];
if (nx < 0 || nx >= rows || ny < 0
|| ny >= cols || grid[nx][ny] == 0){
cnt++;
}
}
}
ans += cnt;
}
}
return ans;
}
}
dfs
思路:遍历网格找到值为1的格子,然后进行深度优先搜索,将走过的格子值变为2,以防止死循环。每经过一个格子对其四个方向进行判断,并累加。
class Solution {
int[][] dirs = new int[][]{{1,0},{0,1},{-1,0},{0,-1}};
public int islandPerimeter(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (grid[row][col] == 1) {
return dfs(grid, row, col, rows, cols);
}
}
}
return 0;
}
private int dfs(int[][] grid, int x, int y, int rows, int cols) {
if (x < 0 || x >= rows || y < 0 || y >= cols || grid[x][y] == 0) {
return 1;
}
if (grid[x][y] == 2) {
return 0;
}
grid[x][y] = 2;
int res = 0;
for (int[] dir : dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
res += dfs(grid, nx, ny, rows, cols);
}
return res;
}
}
分类:
leetCode
【推荐】AI 的力量,开发者的翅膀:欢迎使用 AI 原生开发工具 TRAE
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· C#性能优化:为何 x * Math.Sqrt(x) 远胜 Math.Pow(x, 1.5)
· 本可避免的P1事故:Nginx变更导致网关请求均响应400
· 还在手写JSON调教大模型?.NET 9有新玩法
· 复杂业务系统线上问题排查过程
· 通过抓包,深入揭秘MCP协议底层通信
· AI 的力量,开发者的翅膀:欢迎使用字节旗下的 AI 原生开发工具 TRAE
· 「闲聊文」准大三的我,思前想后还是不搞java了
· C#性能优化:为何 x * Math.Sqrt(x) 远胜 Math.Pow(x, 1.5)
· 千万级的大表如何新增字段?
· 《HelloGitHub》第 112 期
2019-10-30 AndroidStudio 3.4.2配置 Opencv 3.7