Time Limit: 1000 MS Memory Limit: 32768 KB
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
一个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)
Source
POJ
开一个等大的结构体数组,存放目前点的前面的点的数据,最后dfs输出。
#include<iostream>
#include<queue>
using namespace std;
int next[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
struct loc{
int x;
int y;
}locc;
struct father{
int perx;
int pery;
}lj[10][10];
bool map[10][10];
queue<loc> qu;
void dfs(int x,int y)
{
if(x==-1&&y==-1)
{
//cout<<1<<endl;
//cout<<"("<<0<<", "<<0<<")"<<endl;
return;
}
dfs(lj[x][y].perx,lj[x][y].pery);
//cout<<1<<endl;
cout<<"("<<x<<", "<<y<<")"<<endl;
}
int main()
{
int xx,yy;
bool flag=0;
for(int i=0;i<5;++i)
{
for(int j=0;j<5;++j)
{
cin>>map[i][j];
}
}
locc.x=0;
locc.y=0;
lj[0][0].perx=-1;
lj[0][0].pery=-1;
qu.push(locc);
map[0][0]=1;
while(!qu.empty())
{
for(int i=0;i<4;++i)
{
xx=qu.front().x+next[i][0];
yy=qu.front().y+next[i][1];
if(xx<0||xx>=5||yy<0||yy>=5)
continue;
if(!map[xx][yy])
{
map[xx][yy]=1;
locc.x=xx;
locc.y=yy;
qu.push(locc);
lj[xx][yy].perx=qu.front().x;
lj[xx][yy].pery=qu.front().y;
}
if(xx==4&&yy==4)
{
//cout<<1<<endl;
dfs(4,4);
flag=1;
break;
}
}
if(flag) break;
qu.pop();
}
/*for(int i=0;i<5;++i)
{
for(int j=0;j<5;++j)
{
cout<<lj[i][j].perx<<lj[i][j].pery<<" ";
}
cout<<endl;
}*/
return 0;
}
博客围绕用C++编程解决迷宫最短路径问题展开。给定一个5×5二维数组表示迷宫,1为墙壁,0为通路,只能横竖移动。要求找出从左上角到右下角的最短路线,可开等大结构体数组存前置点数据,最后用dfs输出。
590

被折叠的 条评论
为什么被折叠?



