Share my easy understanding Java DFS solution.


  • 0
    O
    public class Solution {
    private int num = 0;
    private boolean[][] visited;
    private void dfs(char[][] grid, int i, int j) {
        if(visited[i][j])
            return;
        visited[i][j] = true;
        if(j - 1 >= 0 && grid[i][j - 1] == '1' && !visited[i][j - 1])
            dfs(grid, i, j -1);
        if(i - 1 >= 0 && grid[i - 1][j] == '1' && !visited[i - 1][j])
            dfs(grid, i - 1, j);
        if(j + 1 < grid[0].length && grid[i][j + 1] == '1' && !visited[i][j + 1])
            dfs(grid, i, j + 1);
        if(i + 1 < grid.length && grid[i + 1][j] == '1' && !visited[i + 1][j])
            dfs(grid, i + 1, j);
    }
    public int numIslands(char[][] grid) {
        if(grid.length == 0)
            return 0;
        visited = new boolean[grid.length][grid[0].length];
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[0].length; j++) {
                if(!visited[i][j] && grid[i][j] == '1'){
                    num++;
                    dfs(grid, i, j);
                }
            }
        }
        return num;
    }
    

    }


Log in to reply
 

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