Simple & Intuitive Java Solution with Explanation


  • 0
    C

    There are posted solutions that adds 4 first and then minus 2's, which I don't think is very intuitive.

    My solution is to simply check 4 directions for each island element, if the current element is 1 (island), check its top, bottom, left, right elements, and add 1 for each 0, which means that side is an edge of the island.

    The only thing need to be specially minded is for elements on the edge of the matrix, because they can have no top/bot/left/right elements. To avoid IndexOutOfBoundsExceptions, we check first if this element is on the edge of the matrix. If yes, then that side is also considered the border of the island.

    public class Solution {
        public int islandPerimeter(int[][] grid) {
            if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
            
            int p = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == 0) continue;
                    if (i == 0 || grid[i - 1][j] == 0) p++;
                    if (j == 0 || grid[i][j - 1] == 0) p++;
                    if (i == grid.length - 1 || grid[i + 1][j] == 0) p++;
                    if (j == grid[0].length - 1 || grid[i][j + 1] == 0) p++;
                }
            }
            
            return p;
        }
    }
    

Log in to reply
 

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