class Solution {
int[] dx = new int[]{0, 0,1,-1};
int[] dy = new int[]{1,-1,0, 0};
int sx,sy,ex,ey;
int m,n;
int res = 0;
int[][] grid;
public int uniquePathsIII(int[][] grid) {
this.grid = grid; //shallow copy
int cnt = 0;
m = grid.length;
n = grid[0].length;
// int cnt = 0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]==1){
sx = i;
sy = j;
}else if(grid[i][j]==2){
ex = i;
ey = j;
}
if(grid[i][j] != -1){
cnt++; //计算有多少可以走的格子
}
}
}
res = 0;
dfs(sx,sy,cnt);
return res;
}
public void dfs(int x, int y, int cnt){
cnt--;
if(cnt < 0) return; //递归出口
if(x==ex && y==ey){ //只要路过终点就不用再往下深入了,注意此处条件的写法
if(cnt==0)
res++;
return;
}
grid[x][y] = 3;
for(int i=0;i<4;i++){
int xx = x+dx[i];
int yy = y+dy[i];
if(xx>=0 && yy>=0 && xx<m && yy<n){
if(grid[xx][yy]==0 || grid[xx][yy]==2){
dfs(xx,yy,cnt);
}
}
}
grid[x][y] = 0; //recursion
}
}