Java easy and concise solution


  • 1
    X

    Check the grid line by line, when we find the edge island '1', we check whether there is neighbor surrounding it or not.

    public int checkNeighbor(int[][] grid, int i, int j)
    {
        int per = 4;
        if(i - 1 >= 0 && grid[i- 1][j] == 1) per --;
        if(j - 1 >= 0 && grid[i][j-1] == 1) per --;
        if(i + 1 < grid.length && grid[i + 1][j] == 1) per --;
        if(j + 1 < grid[0].length && grid[i][j + 1] == 1) per --;
        
        return per;
    }
    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 += checkNeighbor(grid, i , j);
        }
        
     return res;    
    }

Log in to reply
 

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