深度优先搜索算法:回溯算法

这个是前两天搞的那个深度优先算法的进阶版本:

问题描述已经在下面了,接下来是实现代码:

//回溯算法 通常是与深度优先搜索算法绑定的算法

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;
}

输入样例:
3

输出:
1:1,1->1,2->1,3->2,3->3,3
2:1,1->1,2->1,3->2,3->2,2->3,2->3,3
3:1,1->1,2->1,3->2,3->2,2->2,1->3,1->3,2->3,3
4:1,1->1,2->2,2->2,3->3,3
5:1,1->1,2->2,2->3,2->3,3
6:1,1->1,2->2,2->2,1->3,1->3,2->3,3
7:1,1->2,1->2,2->2,3->3,3
8:1,1->2,1->2,2->3,2->3,3
9:1,1->2,1->2,2->1,2->1,3->2,3->3,3
10:1,1->2,1->3,1->3,2->3,3
11:1,1->2,1->3,1->3,2->2,2->2,3->3,3
12:1,1->2,1->3,1->3,2->2,2->1,2->1,3->2,3->3,3

不太好理解,明天在会在帮助理解的同时再加上新内容

posted @ 2025-07-25 21:41  暗神酱  阅读(6)  评论(0)    收藏  举报