迭代
class Solution {
public int islandPerimeter(int[][] grid) {
int res = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
if (i == 0 || grid[i - 1][j] == 0) res++;
if (i == grid.length - 1 || grid[i + 1][j] == 0) res++;
if (j == 0 || grid[i][j - 1] == 0) res++;
if (j == grid[0].length - 1 || grid[i][j + 1] == 0) res++;
}
}
}
return res;
}
}
递归
class Solution {
static int[] dx = {0, 1, 0, -1};
static int[] dy = {1, 0, -1, 0};
public int islandPerimeter(int[][] grid) {
int row=grid.length;
int col=grid[0].length;
int sum=0;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(grid[i][j]==1){
sum+=dfs(grid,i,j);
}
}
}
return sum;
}
public int dfs(int[][] grid,int i,int j) {
int row=grid.length;
int col=grid[0].length;
if(i<0||j<0||i>=row||j>=col||grid[i][j]==0){
return 1;
}
if(grid[i][j]==2){
return 0;
}
grid[i][j]=2;
return dfs(grid,i+1,j)+dfs(grid,i-1,j)+dfs(grid,i,j+1)+dfs(grid,i,j-1);
}
}