1.题意
输入一个5*5的二维数组,仅由0,1两数字组成,0表示可以走,1表示不可以走,要求输出从左上角到右下角的最短路径依次经过的坐标(数据保证有唯一解)
2.样例
Sample Input:
0 1 0 0 0
0 1 0 1 0
0 1 0 1 0
0 0 0 1 0
0 1 0 1 0
Sample Output:
(0, 0)
(1, 0)
(2, 0)
(3, 0)
(3, 1)
(3, 2)
(2, 2)
(1, 2)
(0, 2)
(0, 3)
(0, 4)
(1, 4)
(2, 4)
(3, 4)
(4, 4)
注:坐标(x, y)表示第x行第y列,行、列的编号从0开始,且以左上角为原点。
3.解题思路
分析:
这是一道典型的BFS题,类似于树的按层遍历,访问初始点(0,0),并将其标记为已访问过,再访问(0,0)的所有未被访问过可到达的邻接点,并均标记为已访问过,将这些点加入到队列中,再按照队列中的次序,访问每一个顶点的所有未被访问过的邻接点,将可到达的标记为已访问过,加入队列,以此类推直到遇到终点。
关于输出问题,可以采用并查集的思想,记录加入队列结点的父节点,可以利用map来记录其父节点,最后利用栈的先进后出原理,依次输出最短路径途径坐标
4.总结
1.BFS:利用队列来标记是否已到达过,需要判断是否越界,是否可走,是否到达终点
2.输出路径:用map记录其父节点,利用栈先进后出特性依次输出即可
5.AC代码
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<map>
using namespace std;
struct point{
int x;
int y;
bool operator <(const point &s) const{
return x!=s.x ? x<s.x : y<s.y;
}
bool operator !=(const point &s) const{
return x!=s.x || y!=s.y;
}
};
map<point,point> m;
point father[5][5];
int visit[5][5];
int rode[5][5];
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
int bfs()
{
queue<point> q;
point t;
t.x=0;
t.y=0;
q.push(t);
memset(visit,-1,sizeof visit);
visit[0][0]=0;
while(!q.empty())
{
point now=q.front();
q.pop();
if(now.x==4&&now.y==4) return visit[4][4];
for(int i=0;i<4;i++)
{
int new_x=now.x+dx[i];
int new_y=now.y+dy[i];
if(new_x>=0&&new_x<=4&&new_y>=0&&new_y<=4&&visit[new_x][new_y]==-1&&rode[new_x][new_y]==0)
{
visit[new_x][new_y]=visit[now.x][now.y]+1;
point temp;
temp.x=new_x;
temp.y=new_y;
m[temp]=now;
q.push(temp);
}
}
}
return visit[4][4];
}
int main()
{
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
cin>>rode[i][j];
}
}
bfs();
point end;
point start;
stack<point> r;
start.x=0;
start.y=0;
end.x=4;
end.y=4;
while(m[end]!=start)
{
r.push(end);
end=m[end];
}
r.push(end);
r.push(start);
while(!r.empty())
{
cout<<"("<<r.top().x<<", "<<r.top().y<<")"<<endl;
r.pop();
}
return 0;
}