深度剖析回溯算法和深度优先搜索算法
include<bits/stdc++.h>
int n=0;
bool mark[6][6];
int path[26][3];
int pathcount=0;
int dx[5]={0,0,1,0,-1};
int dy[5]={0,1,0,-1,0};
void print_path(int k)
{
pathcount++;
cout<<pathcount<<":";
for(int i=1;i<k;i++)
{
cout<<path[i][1]<<","<<path[i][2]<<"->";
}
cout<<path[k][1]<<","<<path[k][2]<<endl;
}
void dfs(int x, int y, int k)
{
path[k][1] = x;
path[k][2] = y;
if (x == n && y == n)
{
print_path(k);
return;
}
for (int i = 1; i <= 4; i++)
{
int tx = x + dx[i];
int ty = y + dy[i];
if (!mark[tx][ty] && tx >= 1 && tx <= n && ty >= 1 && ty <= n)
{
mark[tx][ty] = true;
dfs(tx, ty, k + 1);
mark[tx][ty] = false;
}
}
}
int main()
{
cin>>n;
mark[1][1]=true;
dfs(1,1,1);
system("pause");
return 0;
}
通过vs的逐句推理,回溯算法的实现机理:
1.当第一次到达终点时,会利用一次print_path()函数,巧就巧在该函数中有一个return步骤,而执行完这个return之后只是结束了有限个dfs()递归函数的最后一个,会回退到倒数第二个dfs(),此时倒数第二个dfs()函数默认运行结束,会进行dfs()函数之后的下一条语句,也就是mark[tx][ty] = false; 即 把走过的路径再次设置为未走过,进行下一个循环,然后走上一次走过路径的下一条路径,依次类推
2.当回退到上一个dfs()函数中发现没有可选择的路径之后,会由于递归函数本身的性质,当一条路走不通时自动回退到上一条路,直到找到可以走得通的路为止。
依照上面两条规则,就组成了回溯算法和深度优先搜索算法的基本思想,这就是深度优先搜索算法和回溯算法组合的深度剖析。
结束了... 😃
浙公网安备 33010602011771号