迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10850 | Accepted: 6473 |
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
int maze[5][5] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, };
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)题意:输出一条从左上到右下的最短路径。
思路:bfs保存路径。
代码:
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
#define maxn 10
int s[maxn][maxn];
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
struct Node{
int x,y;
int pathx[20];
int pathy[20];
int cnt;
}ans;
void bfs(){
queue<Node> que;
bool v[maxn][maxn];
memset(v,false,sizeof v);
Node node;
node.x = 0, node.y = 0, node.pathx[0] = 0, node.pathy[0] = 0, node.cnt=1;
que.push(node);
while(!que.empty()){
node = que.front();
que.pop();
if(node.x==4 && node.y==4){
ans = node;
return;
}
for(int i=0;i<4;i++){
int xx = node.x + dx[i], yy = node.y+dy[i];
if(xx>=0 && xx<5 && yy>=0 && yy<5 &&s[xx][yy]==0 && !v[xx][yy]){
Node temp = node;
temp.x = xx, temp.y = yy, temp.pathx[temp.cnt] = xx, temp.pathy[temp.cnt] = yy;
temp.cnt++;
que.push(temp);
v[xx][yy] = true;
}
}
}
}
int main(){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
scanf("%d",&s[i][j]);
}
}
bfs();
for(int i=0;i<ans.cnt;i++){
printf("(%d, %d)\n",ans.pathx[i],ans.pathy[i]);
}
return 0;
}