dfs入门题
#include <iostream>
using namespace std;
void print(int);
int map[5][5];
struct pos{
int x,y;
int pre;
};
pos list[200];
int dy[4] = {1,-1,0,0};
int dx[4] = {0,0,1,-1};
int main()
{
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
cin>>map[i][j];
}
}
int f=0,r=1,x,y;
list[0].x = 0;
list[0].y = 0;
list[0].pre = -1;
while(!(list[f].x==4&&list[f].y==4))
{
map[list[f].x][list[f].y] = 1;
for(i=0;i<4;i++)
{
x = list[f].x+dx[i];
y = list[f].y + dy[i];
if(map[x][y]||x<0||x>4||y<0||y>4)
continue;
list[r].x = x;
list[r].y = y;
list[r].pre = f;
r++;
}
f++;
}
print(f);
return 0;
}
void print(int n)
{
if(n==-1)
return;
else
{
print(list[n].pre);
cout<<'('<<list[n].x<<", "<<list[n].y<<')'<<endl;
}
}
本文介绍了一个使用深度优先搜索(DFS)算法解决迷宫寻路问题的C++实现案例。该程序通过递归的方式遍历迷宫地图,寻找从起点到终点的路径,并能够输出路径上的坐标点。
308

被折叠的 条评论
为什么被折叠?



