DFS 其实就是一直顺着一个方向不断的搜索直到找到了目标为止。路径输出的时候,利用记录前面的点即可。
举例:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 9
int cnt;
struct Point{
int x;
int y;
}path[N*N];
int maze[N][N];/*保存地图*/
int vis[N][N];/*标记哪一个点是否被访问过*/
int dir[4][2] = {
{-1,0},{0,1},{1,0},{0,-1}};/*方向数组*/
Point star , end;
/*路径输出,只要找到了目标就可以输出*/
void output(){
printf("(%d , %d)->" , star.x , star.y);
for(int i = 1 ; i < cnt-1 ; i++)
printf("(%d , %d)->" , path[i].x , path[i].y);
printf("(%d , %d)\n\n" , end.x , end.y);
printf("\n");
}
/*深搜*/
void DFS(int x , int y , int step){
int tmp_x , tmp_y;
Point p;
/*如果找到了目标,就调用output函数输出路径,然后return*/
if(x == end.x && y == end.y){
cnt = step;
output();
r