Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6410 | Accepted: 3741 |
Description
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
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)
Source
看了很久的数据结构,老是觉得光说不练是假把戏,还真是,看了,只会理论上的东西,动手能力没有提高。呵呵,所以就拿了这道题目来练练手了。
AC掉了的代码:
#include<iostream>
#include<string.h>
using namespace std;
int Map[5][5];//用于存储迷宫;
bool vs[5][5];//用于标记某个节点是否被访问过;
int st=1;
int en=1;//用于标记队列的头和尾巴;
bool F=false;
struct Node{
int x;
int y;
int from;//用于标记当前节点是从哪里来的;
}Queue[405];//用数组来模仿队列;
int dx[4]={0,0,1,-1};
int dy[4]={-1,1,0,0};
int main()
{
//memset(vs, false, sizeof(vs));
int i;
int j;
int x,y;
for(i=0; i<5; i++)
{
for(j=0; j<5; j++)
cin>>Map[i][j];
}
Queue[1].x=4;
Queue[1].y=4;//从后面往前面搜索;
Queue[1].from=0;
while(st<=en)
{
for(i=0; i<4; i++)
{
x=Queue[st].x+dx[i];//立足当前节点,往四周探索是否可以走,
y=Queue[st].y+dy[i];
if(0<=x&&x<5&&0<=y&&y<5&&!vs[x][y]&&Map[x][y]==0)
{
vs[x][y]=true;
en++;
Queue[en].x=x;
Queue[en].y=y;
Queue[en].from=st;
if(x==0 && y==0)
F=true;
}
}
if(F==true)
break;
st++;
}
while(en)
{
cout<<"("<<Queue[en].x<<", "<<Queue[en].y<<")"<<endl;
en=Queue[en].from;
}
return 0;
}