| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 8089 | Accepted: 4765 |
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,
};
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)本题关键在于输出路径,,方法是利用一个father数组记录父节点,再逆向存入新的数组,正向输出。
father[nx*5+ny]=p.first*5+p.second;
a[j++]=father[k];
k=father[k];
这里形成一中环环相扣,最后一个数组是father[24]{4,4}它存储着上一个位置的值x*5+y,而这一个又存储着它的上一个。。。直到k=0{0,0}。
#include<iostream>
#include<queue>
using namespace std;
int maze[5][5];
int d[5][5];
const int INF=1000;
int father[30];
typedef pair<int,int> P;
int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};
void print()
{
int a[30];
int j=0,k=24;
while(k!=0)
{
a[j++]=father[k];
k=father[k];
}
for(int i=j-1;i>=0;i--)
cout<<"("<<a[i]/5<<", "<<a[i]%5<<")"<<endl;
cout<<"(4, 4)"<<endl;
}
void bfs(int x,int y)
{
maze[x][y]=-1;
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
d[i][j]=INF;
queue<P>que;
que.push(P(0,0));
d[0][0]=0;
while(que.size())
{
P p = que.front();
que.pop();
if(p.first == 4&&p.second == 4)
{
print();
break;
}
for(int i=0;i<4;i++){
int nx=p.first+dx[i],ny=p.second+dy[i];
if(0<=nx&&nx<5&&0<=ny&&ny<5&&maze[nx][ny]==0&&d[nx][ny]==INF)
{
que.push(P(nx,ny));
father[nx*5+ny]=p.first*5+p.second;
d[nx][ny]=d[p.first][p.second]+1;
}
}
}
// return d[4][4]; 返回最短路径数
}
int main()
{
int i,j;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
cin>>maze[i][j];
bfs(0,0);
return 0;
}这里通过一个二维数组记录(d[nx][ny]=d[p.first][p.second]+1;)到达每个位置所需行走的最短长度,,可以返回最短路径值,但本题不作要求。
原文地址:http://blog.csdn.net/u014492609/article/details/40114445