463. Island Perimeter
1 class Solution { 2 public int islandPerimeter(int[][] grid) { 3 if(grid == null) return 0; 4 int row = grid.length; 5 if(row == 0) return 0; 6 int col = grid[0].length; 7 int res = 0; 8 for(int i = 0; i < row; i++) { 9 for(int j = 0; j < col; j++) { 10 if(grid[i][j] == 1) { 11 res += 4; 12 if(i+1 < row && grid[i+1][j] == 1) { 13 res -= 1; 14 } 15 if(i-1 >= 0 && grid[i-1][j] == 1) { 16 res -= 1; 17 } 18 if(j+1 < col && grid[i][j+1] == 1) { 19 res -= 1; 20 } 21 if(j-1 >= 0 && grid[i][j-1] == 1) { 22 res -= 1; 23 } 24 } 25 } 26 } 27 return res; 28 29 } 30 }