POJ-3984-迷宫问题
来源:互联网 发布:淘宝牛仔裤女 编辑:程序博客网 时间:2024/06/02 12:56
迷宫问题
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64uDescription
定义一个二维数组:
它表示一个迷宫,其中的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)
这道题的难点在于状态的保存。用bfs是从最初的状态一直到最后状态,每一个状态都要保存前一个状态,这样才能保存路径,
怎么保存状态呢?起初我想用链表,有点麻烦,所以用数组代替链表,就是开一个struct数组,记录当前节点编号,和上一节点编号,根据编号找到上一个节点,这样子就在找到最短路径是从最后一个节点一直推会起点。
#include<iostream>#include<cstdio>#include<queue>#include<stack>#include<vector>#include<algorithm>#define maxn 15#define inf 0x3f3f3f3fusing namespace std;int m,n;int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};int mp[maxn][maxn];bool vis[maxn][maxn];struct node{int x,y;int num;int last;node(int x=0,int y=0,int num=0,int last=0):x(x),y(y),num(num),last(last){};}pre[1005];bool judge(int x,int y){ if(x>=0&&y>=0&&x<5&&y<5&&!vis[x][y]&&mp[x][y]==0)return true; return false;}node bfs(){ queue<node>q; int j=1; pre[1]=node(0,0,1,0); q.push(pre[1]); while(!q.empty()){ node temp=q.front(); q.pop(); if(temp.x==4&&temp.y==4)return temp; for(int i=0;i<4;i++){ int nx=temp.x+dir[i][0]; int ny=temp.y+dir[i][1]; if(judge(nx,ny)){ vis[nx][ny]=1; j++; pre[j]=node(nx,ny,j,temp.num); q.push(pre[j]); } } }}stack<node> getpath(node a){ stack<node>st; while(a.num!=NULL){ st.push(a); a=pre[a.last]; } return st;}int main(){ //freopen("in.txt","r",stdin); memset(vis,0,sizeof vis); for(int i=0;i<5;i++) for(int j=0;j<5;j++) scanf("%d",&mp[i][j]); node a=bfs(); stack<node> b=getpath(a); while(!b.empty()){ printf("(%d, %d)\n",b.top().x,b.top().y); b.pop(); }}
0 0
- poj 3984 迷宫问题
- poj 3984 迷宫问题
- POJ-3984-迷宫问题
- Poj 3984 迷宫问题
- 迷宫问题 poj 3984
- poj 3984迷宫问题
- poj 3984 迷宫问题
- POJ-3984-迷宫问题
- poj 3984- 迷宫问题
- POJ 3984 迷宫问题
- poj 3984 迷宫问题
- poj 3984:迷宫问题
- POJ-3984-迷宫问题
- POJ 3984 迷宫问题
- poj 3984迷宫问题
- POJ 3984 迷宫问题
- POJ 3984 迷宫问题
- poj 3984 迷宫问题
- PAT 04-2. File Transfer (25) (并查集)
- java面向对象和类
- iReport 按某个字段(属性)值分页打印
- reason: 'Could not load NIB in bundle: "XXXXXXX" with name 'xxCell'
- my git log
- POJ-3984-迷宫问题
- Android开发优化之——从代码角度进行优化
- CentOS7 ping通 telnet不通
- 深入理解Arrays.sort()
- {A} + {B}
- iOS 根据不同的系统版本加载不同图片方法
- iOS:堆(heap)和栈(stack)的理解
- 4K显示器和防蓝光眼镜膜
- linux 文件系统入门简介