https://leetcode.cn/problems/island-perimeter/description/
思路:遍历岛屿,一旦遍历到边界或者水则周长++
class Solution {
int res;
boolean[][] vis;
int[][] grid;
int[] dx=new int[]{0,1,0,-1};
int[] dy=new int[]{1,0,-1,0};
int n;
int m;
public int islandPerimeter(int[][] grid) {
n=grid.length;
m=grid[0].length;
this.grid=grid;
vis=new boolean[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
if(grid[i][j]==1)
{
dfs(i,j);
return res;
}
}
return 0;
}
void dfs(int x,int y)
{
vis[x][y]=true;
for(int i=0;i<4;i++)
{
int a=x+dx[i],b=y+dy[i];
if(a<0 || b<0 || a>=n || b>=m || grid[a][b]==0)
{
// 遍历到边界或者水都是 周长++
res++;
continue;
}
if(a>=0 && b>=0 && a<n && b<m && vis[a][b]==false && grid[a][b]==1)
{
dfs(a,b);
}
}
}
}
标签:周长,int,463,++,grid,new,leetcode From: https://www.cnblogs.com/lxl-233/p/18450372