My DFS solution for unique paths


  • 0
    J

    anyone can improve my code?

    public class Solution {
                static int[][] count = new int[105][105];
                static boolean[][] visited = new boolean[105][105];
            public int uniquePaths(int m, int n) {
                if(m <= 1 || n <= 1) return 1;
                else return DFS(m - 1, n - 1);
            }
            
            public int DFS(int i, int j){
                int res = -1;
                if(visited[i][j] == true && i >= 0 && j >= 0) res = count[i][j];
                else if(visited[i][j] == false && i >= 0 && j >= 0){
                    visited[i][j] = true; 
                    if((i == 0 && j == 1) || (i == 1 && j == 0)) {
                        count[0][1] = count[1][0] = 1;
                        return 1;
                    }
                    else if(i == 0 && j != 1) res = count[i][j] = DFS(i,j - 1);
                    else if(j == 0 && i != 1) res = count[i][j] = DFS(i - 1, j);
                    else res = count[i][j] = DFS(i - 1, j) + DFS(i, j - 1);
                }
                return res;
            }
        }

Log in to reply
 

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