Java DFS easy to understand solution


  • 0
    S
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            int perimeter = 0;
            int row = grid.length;
            int col = grid[0].length;
            boolean[][] visited = new boolean[row][col];
            for(boolean[] i : visited){
                Arrays.fill(i,false);
     
            }
            for(int i = 0; i<row; i++){
                for(int j = 0; j<col; j++){
                    if(visited[i][j] == false && grid[i][j] == 1){
                        perimeter = perimeter + dfs(grid,visited,i,j,0);
                    }
                }
            } 
            return perimeter;
        }
        
        public int dfs(int[][] grid, boolean[][] visited, int i, int j,int per){
            int row = grid.length;
            int col = grid[0].length;
             visited[i][j] = true;
            if(i== 0  &&  grid[i][j] == 1 ){
                per++;
            } 
            if(j == 0  && grid[i][j] == 1 ){
                per++;
            }
            if(i == row-1 && grid[i][j] == 1){
                per++;
            }
            if(j == col-1 && grid[i][j] == 1){
                per++;
            }
            if(i>0 && grid[i-1][j] == 0 && !visited[i-1][j]){
                per++;
            } 
            if(i+1<row && grid[i+1][j] == 0 && !visited[i+1][j]){
                per++;
            } 
            if(j>0 && grid[i][j-1] == 0 && !visited[i][j-1]){
                per++;
            } 
            if(j+1 < col && grid[i][j+1] == 0 && !visited[i][j+1]){
                per++;
            }
                   
    
            return per;
        }
    }
    

Log in to reply
 

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