题意:给定一个二维数组,1为岛屿,0为水,计算岛屿的周长
思路:dfs遍历每一个为1的节点,并对每一个为1的节点的上下左右遍历,如果相邻的为0或者溢出了数组,结果+1
思想:dfs
复杂度:时间O(n2),空间O(n2)
class Solution {
int sum =0;
public int islandPerimeter(int[][] grid) {
int m = grid.length;
if(m == 0)
return 0;
int n = grid[0].length;
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
if(grid[i][j] == 1) {
boolean[][] visited = new boolean[m][n];
dfs(grid, i, j, m, n, visited);
return sum;
}
}
}
return 0;
}
void dfs(int[][] grid, int i, int j, int m, int n, boolean[][] visited) {
if(i<0||j<0||i>=m||j>=n||visited[i][j]||grid[i][j] == 0) {
return;
}
visited[i][j] = true;
if(i - 1 < 0)
sum++;
if(i + 1 >= m)
sum++;
if(j-1<0)
sum++;
if(j+1 >= n)
sum++;
if(i-1>=0) {
if(grid[i-1][j] == 1) {
dfs(grid,i-1,j,m,n,visited);
} else {
sum++;
}
}
if(j-1>=0) {
if(grid[i][j-1] == 1) {
dfs(grid,i,j-1,m,n,visited);
} else {
sum++;
}
}
if(i+1<m) {
if(grid[i+1][j] == 1) {
dfs(grid,i+1,j,m,n,visited);
} else {
sum++;
}
}
if(j+1<n) {
if(grid[i][j+1] == 1) {
dfs(grid,i,j+1,m,n,visited);
} else {
sum++;
}
}
}
}
网友评论