Java DFS Clean code


  • 0
    S

    Clean code for java dfs solution:

    '''

    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
        if (maze == null || maze.length == 0 || maze[0].length == 0) {
            return false;
        }
        int m = maze.length;
        int n = maze[0].length;
        boolean[][] visited = new boolean[m][n];
        return dfs(visited, maze, start, destination);
    }
    
    public boolean dfs(boolean[][] visited, int[][] maze, int[] start, int[] destination) {
        int i = start[0];
        int j = start[1];
        if (visited[i][j]) {
            return false;
        }
        if (i == destination[0] && j == destination[1]) {
            return true;
        }
        visited[i][j] = true;
        int[][] dirs = {{1,0},{0,1},{-1,0},{0,-1}};
        for (int[] dir : dirs) {
            int x = i;
            int y = j;
            while (x + dir[0] >= 0 && x + dir[0] < maze.length && y + dir[1] >= 0 && y + dir[1] < maze[0].length && maze[x + dir[0]][y + dir[1]] == 0) {
                x +=dir[0];
                y +=dir[1];
            }
            if (dfs(visited, maze, new int[]{x, y}, destination)) {
                return true;
            }
        }
        return false;
    }
    

    '''


Log in to reply
 

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