这题飞机上写的。边界条件蛮多的,以为会错但竟然一次AC了。
如果我不知道这是一道easy题,应该就想不出来了。。
public int islandPerimeter(int[][] grid) {
int res = 0;
for (int row = 0; row < grid.length; row++)
for (int col = 0; col < grid[0].length; col++) {
if (grid[row][col] == 1) {
res += calc(row, col, grid);
}
}
return res;
}
private int calc(int row, int col, int[][] matrix) {
int count = 0;
if (row == 0 || row > 0 && matrix[row - 1][col] == 0) {
count++;
}
if (col == 0 || col > 0 && matrix[row][col - 1] == 0) {
count++;
}
if (row == matrix.length - 1 || row < matrix.length - 1 && matrix[row + 1][col] == 0) {
count++;
}
if (col == matrix[0].length - 1 || col < matrix[0].length - 1 && matrix[row][col + 1] == 0) {
count++;
}
return count;
}
另外看到一种计算right neighbor 和 down neighhor最后统一处理的方法:
https://discuss.leetcode.com/topic/68786/clear-and-easy-java-solution