463. Island Perimeter
Input:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:
解题要点:
Last updated
Input:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:
Last updated
class Solution {
public int islandPerimeter(int[][] grid) {
if (grid == null || grid.length == 0)
return 0;
int res = 0;
int temp = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] == 1){
res++;
if(i > 0 && grid[i-1][j] == 1) temp++;
if(i < grid.length - 1 && grid[i+1][j] == 1) temp++;
if(j > 0 && grid[i][j-1] == 1) temp++;
if(j < grid[0].length - 1 && grid[i][j+1] == 1) temp++;
}
}
}
return res*4 - temp;
}
}