迷宫求解
?
任務:可以輸入一個任意大小的迷宮數據,用非遞歸的方法求出一條走出迷宮的路徑,并將路徑輸出;
#include <iostream>
#include <stack>
using namespace std;
?
#define N 100
typedef struct vex{ ?
int x;
int y;
}vex;
?
int n, m;
stack <vex> s;
int visited[N+1][N+1];
int map[N+1][N+1];
vex a, b, c, d;
int dir[4][2] = {1,0,0,1,-1,0,0,-1};
?
int main()
{ ?
int i, j; ?
int x, y; ?
stack <vex> Q; ?
while (!s.empty()) ?
{
s.pop(); ?
} ?
cout<<"請輸入迷宮的大小(0代表能走通,1代表不能走通):"; ?
cin>>n>>m; ?
for (i=0; i<n; i++) ??
for (j=0; j<m; j++) ??
{
cin>>map[i][j]; ???
visited[i][j] = 0; ??
}??
cout<<"請輸入起點坐標和終點坐標:";
loop:cin>>a.x>>a.y>>b.x>>b.y; ?
d = a; ?
if (map[a.x-1][a.y-1]!=0 || map[b.x-1][b.y-1]!=0) ?
{
cout<<"輸入的坐標無效,請重新輸入"<<endl; ??
goto loop; ?
} ?
s.push(a); ?
visited[a.x-1][a.y-1] = 1; ?
while (!s.empty()) ?
{ ??
d = s.top(); ?
if (d.x==b.x && d.y==b.y) ???
break; ??
for (i=0; i<4; i++) ??
{ ???
x = d.x-1+dir[i][0]; ???
y = d.y-1+dir[i][1]; ??
? if ((x<0) || (y<0) || (x>=m) || (y>=n)) ????
continue; ???
if (map[x][y]==0 && visited[x][y]==0) ???
{ ????
c.x = x+1; ????
c.y = y+1; ????
s.push(c); ????
visited[x][y] = 1; ????
break; ???
}
}???
if (i == 4) ??
{
d = s.top(); ???
map[d.x-1][d.y-1] = 1; ???
s.pop(); ??
} ?
}?
?
? if (s.empty()) ?
{ ??
cout<<"沒有找到路徑"<<endl; ?
} ?
else ?
{? ?
? while (!s.empty()) ??
{ ???
Q.push(s.top()); ???
s.pop(); ??
} ??
c = Q.top(); ??
cout<<"("<<c.x<<","<<c.y<<")"; ?
? Q.pop(); ??
while (!Q.empty()) ??
{ ???
c = Q.top(); ???
Q.pop(); ???
cout<<"->("<<c.x<<","<<c.y<<")"; ?
? } ??
cout<<endl; ?
}
return 0;
}
轉載于:https://www.cnblogs.com/yazhou/p/3485083.html
總結
- 上一篇: 小花钱包上征信吗2020
- 下一篇: 怎么利用flash制作一个电子相册