java solution


  • 0
    J

    we can divide the perimeter into four parts.And then we iterator the grid,if one cell's data is 1,we judge the row number、the column number and the data of its neighbor cells.

      public int islandPerimeter(int[][] grid) {
            int count = 0;
            if(grid == null){
                return count;
            }
            for(int i = 0; i < grid.length; i++){
                for(int j = 0; j < grid[0].length; j++){
                    if(grid[i][j] == 1){
                        if(i == 0 || grid[i-1][j] == 0){//top line
                            count ++;
                        }
                        if(i == grid.length - 1 || grid[i+1][j] == 0){//bottom line
                            count++;
                        }
                        if(j == 0 || grid[i][j-1] == 0){//left line
                            count++;
                        }
                        if(j == grid[0].length - 1 || grid[i][j+1] == 0){//right line
                            count++;
                        }
                    }
                }
            }
            return count;
        }
    

Log in to reply
 

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