1. Title
Ideas (description in Java language)
The classic DFS+backtracking algorithm, the restriction condition of this problem is that you need to calculate the number of 0 in the two-dimensional array, plus this conditional judgment.
class Solution {
//0 1
//2 0
int rowLen;
int colLen;
int totalCnt = 0;
public int uniquePathsIII(int[][] grid) {
rowLen = grid.length;
colLen = grid[0].length;
int zeroNum = getZeroNum(grid);
for(int i = 0;i<rowLen;i++){
for(int j = 0;j<colLen;j++){
if(grid[i][j] == 1){
dfs(i,j,grid,0,zeroNum);
break;
}
}
}
return totalCnt;
}
public void dfs(int i,int j,int[][] grid,int temp,int zeroNum){
if(!checkBoard(i,j) || grid[i][j] == -1){
return;
}
if(temp!=zeroNum+1 && grid[i][j] == 2){
return;
}
if(temp == zeroNum+1 && grid[i][j] == 2){
totalCnt++;
return;
}
grid[i][j] = -1;
dfs(i-1,j,grid,temp+1,zeroNum);
dfs(i,j+1,grid,temp+1,zeroNum);
dfs(i+1,j,grid,temp+1,zeroNum);
dfs(i,j-1,grid,temp+1,zeroNum);
grid[i][j] = 0;
}
public int getZeroNum(int[][] grid){
int cnt = 0;
for(int i = 0;i<rowLen;i++){
for(int j = 0;j<colLen;j++){
if(grid[i][j] == 0){
cnt++;
}
}
}
return cnt;
}
public boolean checkBoard(int i,int j){
if(i>=rowLen || i<0) return false;
if(j>=colLen || j<0) return false;
return true;
}
}
to sum up
After writing this question for the first time, the test result is always 0. After thinking about it for a long time, I found that the judgment condition except for the problem, the number of deep search steps (temp) should be equal to zeroNum+1 instead of zeroNum