I'm doing this problem called "Unique Paths" on a site called leetcode. The problem is: given a 2D matrix with 1s and 0s, a robot starts at the top-left and wants to reach the bottom-right. The robot has only 2 moves: right and down. Also, there are obstacles (represented by a '1'). The robot cannot walk over the obstacles. My program is giving me a wrong answer when I give the input:
0000
0100
0000
0000
Which should output 7, because there are 7 paths from the top left square to the bottom right square. My program outputs 2. My guess is that it only goes all the way down and all the way right, and all the way right and all the way down. However, I don't know the cause of this behaviour, as it looks fine to me. Can anyone tell me why it's doing this? Here is the code:
class Solution {
int[][] check;
public int uniquePathsWithObstacles(int[][] grid) {
if(grid == null || grid.length == 0)
return 0;
check = new int[grid.length][grid[0].length];
return uniquePaths(grid, 0, 0);
}
private int uniquePaths(int[][] grid, int x, int y){
if(x >= grid[0].length || y >= grid.length || grid[y][x] == 1)
return 0;
else if(x == grid[0].length - 1 && y == grid.length - 1)
return 1;
else if(check[y][x] > 0)
return check[y][x];
return grid[y][x] = uniquePaths(grid, x + 1, y) + uniquePaths(grid, x, y + 1);
}
}