Java solution, fast & easy to understand.


  • 0
    Z

    Every island has 4 sides, once there is one more other island surrounding it, the sides would minus 1. So what we need to do is just check the number of surrounding islands of every island.

    public int islandPerimeter(int[][] grid) {
        int res = 0;
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == 1)
                    res += checkAroundNum(grid, i, j);
            }
        }
        return res;
    }
    
    public int checkAroundNum (int[][] grid, int row, int col) {
        int perimeter = 4;
        if(row < grid.length-1)
            if(grid[row+1][col]==1) {
                perimeter --;
            }
        if(row > 0)
            if(grid[row-1][col]==1) {
                perimeter --;
            }
        
        if(col < grid[0].length-1)
            if(grid[row][col+1]==1) {
                perimeter --;
            }
        if(col > 0)
            if(grid[row][col-1]==1) {
                perimeter --;
            }
        return perimeter;
    }

Log in to reply
 

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