首页 > 代码库 > 搜索问题——POJ3984迷宫问题
搜索问题——POJ3984迷宫问题
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 00 1 0 1 00 0 0 0 00 1 1 1 00 0 0 1 0
Sample Output
(0, 0)(1, 0)(2, 0)(2, 1)(2, 2)(2, 3)(2, 4)(3, 4)(4, 4)
#include<stdio.h>#include<stdlib.h>int map[5][5];int dir[4][2]={1,0,-1,0,0,1,0,-1};struct node{ int x,y;};struct node queue[50],record[5][5];void bfs(){ int i,head,tail; struct node cur,next; head=tail=0; cur=queue[tail]; tail++; while(head<tail) { cur=queue[head++]; for(i=0;i<4;i++) { next.x=cur.x+dir[i][0]; next.y=cur.y+dir[i][1]; if(next.x>=0&&next.y>=0&&next.x<5&&next.y<5&&map[next.x][next.y]==0) { record[next.x][next.y].x=cur.x; record[next.x][next.y].y=cur.y; if(next.x==4&&next.y==4) return ; else { map[next.x][next.y]=1; queue[tail++]=next; } } } }}int main(){ int i,j,k,m,n; for(i=0;i<5;i++) { for(j=0;j<5;j++) scanf("%d",&map[i][j]); } queue[0].x=0; queue[0].y=0; map[0][0]=1; bfs(); k=0; queue[k].x=4; queue[k++].y=4; i=j=4; while(i!=0||j!=0) { m=i;n=j; i=record[m][n].x; j=record[m][n].y; queue[k].x=i; queue[k++].y=j; } for(i=k-1;i>=0;i--) { printf("(%d, %d)\n",queue[i].x,queue[i].y); } return 0;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。