Java solution with DFS


  • 4
    X
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            if (grid == null) return 0;
            for (int i = 0 ; i < grid.length ; i++){
                for (int j = 0 ; j < grid[0].length ; j++){
                    if (grid[i][j] == 1) {
                        return getPerimeter(grid,i,j);
                    }
                }
            }
            return 0;
        }
        
        public int getPerimeter(int[][] grid, int i, int j){
            if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) {return 1;}
            if (grid[i][j] == 0) {
                return 1;
            }
            if (grid[i][j] == -1) return 0;
            
            int count = 0;
            grid[i][j] = -1;
            
            count += getPerimeter(grid, i-1, j);
            count += getPerimeter(grid, i, j-1);
            count += getPerimeter(grid, i, j+1);
            count += getPerimeter(grid, i+1, j);
            
            return count;
            
        }
    }
    

  • 0
    H

    Good solution, really easy to understand


  • 0
    S

    Could you please explain this
    ``if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) {return 1;}
    if (grid[i][j] == 0) {
    return 1;
    }
    if (grid[i][j] == -1) return 0;"

    why the first two if's return 1? the last if return 0?


Log in to reply
 

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