first version
First version is straight forward, check each unit, and check the four units around it. If they are valid island, continue. else, perimeter increment.
public class Solution {
int[][] grid;
int row;
int col;
public int islandPerimeter(int[][] grid) {
this.grid = grid;
row = grid.length;
if(row == 0)return 0;
col = grid[0].length;
int perimeter = 0;
for(int i = 0; i < row; i ++){
for(int j = 0; j < col; j++){
if(!isIsland(i,j))continue;
if(!isIsland(i - 1, j))perimeter++;
if(!isIsland(i + 1, j))perimeter++;
if(!isIsland(i, j - 1))perimeter++;
if(!isIsland(i, j + 1))perimeter++;
}
}
return perimeter;
}
public boolean isIsland(int i, int j){
if(i < 0 || i >= row || j < 0 || j >= col)return false;
return grid[i][j] == 1;
}
}
Other versions
I see some top solutions on leetcode discussion, and the idea is the same. some optimization is to count 4 for each unit, and when it has a neighbors( right and down directions to avoid repeat), then minus 2, since the two neighbors will share an edge.