Java 理解回溯(网格上的机器人)

Java 理解回溯(网格上的机器人),java,backtracking,Java,Backtracking,以下是在网格上移动的机器人的代码,假设机器人从左上角移动到右下角,并找到到达右下角的独特方式: public static int findNumPath(int row, int col){ int total = 0; //if grid[2][2] is reached, 1 path is found if(row == 2 && col == 2){ return 1; } grid[row][col] = true; print(); if(col <

以下是在网格上移动的机器人的代码,假设机器人从左上角移动到右下角,并找到到达右下角的独特方式:

public static int findNumPath(int row, int col){
int total = 0;

//if grid[2][2] is reached, 1 path is found
if(row == 2 && col == 2){
    return 1;
}
grid[row][col] = true;
print();

if(col < 2 && grid[row][col+1] == false){
    System.out.println("inside 1st if" + " ,total= " + total);
    total = total + findNumPath(row, col+1);
}
if(col > 0 && grid[row][col-1] == false){
    System.out.println("inside 2nd if" + " ,total= " + total);
    total = total + findNumPath(row, col-1);
}
if(row < 2 && grid[row+1][col] == false){
    System.out.println("inside 3rd if" + " ,total= " + total);
    total = total + findNumPath(row+1, col);
}
if(row > 0 && grid[row-1][col] == false ){
    System.out.println("inside 4th if"+ " ,total= " + total);
    total = total + findNumPath(row-1, col);
}

grid[row][col] = false;
System.out.println("after making false" + " total=" + total);
return total;
}
我最近学习了回溯,我试图理解这段代码,回溯是如何运行的,但是我不明白在我们找到第一条路径后发生了什么,程序如何知道返回并使一些真变假:

inside 1st if ,total= 0
after making false total=1
after making false total=1
after making false total=1
inside 3rd if ,total= 1
true true true 
false true true 
false true false 

如果能给我一个解释,我将不胜感激。

上面的代码并不是真正的回溯,而是一个递归搜索算法。它递归地搜索网格,按此顺序移动深度优先、左、右、下、上

当一个字段在其上移动时,它用true标记该字段;当它从该位置用尽所有可能时,它用false标记该字段(对于当前访问的字段)。它标记字段,因为它不会再次访问字段两次,所以它会搜索最多访问每个字段一次的路径

请注意,对于每个指向该字段的路径,它都会再次计算该字段

inside 1st if ,total= 0
after making false total=1
after making false total=1
after making false total=1
inside 3rd if ,total= 1
true true true 
false true true 
false true false