Easy understand solution


  • 0
    G

    count the land neighbors for each land cell. For a land has 4 neighbors, it will have 0 side counted into the perimeter. A land has 3 neighbors, it will have 1 side counted into the perimeter. The side will be counted is just 4 minus its neighbor number.

    public class Solution {
        public int islandPerimeter(int[][] grid) {
            if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
            int result = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == 0) continue;
                    int count = 0;
                    //count the land neighbor number
                    if (i > 0 && grid[i - 1][j] == 1) count++;
                    if (j > 0 && grid[i][j - 1] == 1) count++;
                    if (i < grid.length - 1 && grid[i + 1][j] == 1) count++;
                    if (j < grid[0].length - 1 && grid[i][j + 1] == 1) count++;
                    //add the side number into final result.
                    result += 4 - count;
                }
            }
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.