首页 > 代码库 > LeetCode: Island Perimeter

LeetCode: Island Perimeter

 1 public class Solution {
 2     public int islandPerimeter(int[][] grid) {
 3         int ans = 0;
 4         for (int i = 0; i < grid.length; i++) {
 5             for (int j = 0; j < grid[0].length; j++) {
 6                 if (grid[i][j] == 1) {
 7                     if (i == 0 || (i > 0 && grid[i-1][j] == 0)) ans++;  //top
 8                     if (i == grid.length-1 || (i < grid.length-1 && grid[i+1][j] == 0)) ans++; //bottom
 9                     if (j == 0 || (j > 0 && grid[i][j-1] == 0)) ans++; //left
10                     if (j == grid[0].length-1 || (j < grid[0].length-1 && grid[i][j+1] == 0)) ans++; //right
11                 }
12             }
13         }
14         return ans;
15     }
16 }

 

LeetCode: Island Perimeter