Leetcode463 Island Perimeter
very easy to understand:
Input:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Output: 16
the modified version of flood fill alg, but we need to transfer out mind a little bit.
first, we know that this problem needs to be solved in dfs.
then think of a lonely 1*1 island.
starting from this island, if left of it is water/out of bound, then the left edge belongs to us, count+1
moving to right, if right part is island as well, then this right edge can’t be count as an edge, so count+0
and only when this direction is an island will we continue our dfs.
public class Solution {
public int islandPerimeter(int[][] grid) {
if (grid == null ||grid[0] == null || grid.length == 0) {
return 0;
}
int m = grid.length;
int n = grid[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
return perimeter(grid, i, j);
}
}
}
return 0;
}
private int perimeter(int[][] grid, int i, int j) {
int count = 0; //top level
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) {
return 1;
}
if(grid[i][j] == 0) {
return 1;
}
if (grid[i][j] == -1) { //means we revisied it, and this line will not exist
return 0;
}
grid[i][j] = -1; //mark here to show here is a land, and we don't have edge
count += perimeter(grid, i - 1, j);
count += perimeter(grid, i + 1, j);
count += perimeter(grid, i, j - 1);
count += perimeter(grid, i, j + 1);
return count;
}
}

浙公网安备 33010602011771号