* 东东有一张地图,想通过地图找到妹纸。地图显示,0表示可以走,1表示不可以走,左上角是入口,右下角是妹纸,这两个位置保证为0。既然已经知道了地图,那么东东找到妹纸就不难了,请你编一个程序,写出东东找到妹纸的最短路线。
Input
输入是一个5 × 5的二维数组,仅由0、1两数字组成,表示法阵地图。
Output
输出若干行,表示从左上角到右下角的最短路径依次经过的坐标,格式如样例所示。数据保证有唯一解。
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)
Hint
坐标(x, y)表示第x行第y列,行、列的编号从0开始,且以左上角为原点。
另外注意,输出中分隔坐标的逗号后面应当有一个空格。*
分析:bfs,从起点开始,判断相邻点是否遍历过,若没有,入队列,沿途存下步数dis[],用于打印出路径——建一个栈,从终点开始,当前点记作x1,y1,遍历其相邻点,记作点x2,y2,判断if (dis[x1][y1]==dis[x2][y2] + 1
),若为真,入栈。结束条件:newX == 0 && newY == 0
。
代码如下:
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
struct point
{
int x;
int y;
point(int X = -1, int Y = -1)
{
x = X;
y = Y;
}
};
bool map[5][5];
int dis[5][5];
int dx[4] = { 0,0,-1,+1 };
int dy[4] = { -1,+1,0,0 };
void input()
{
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
cin >> map[i][j];
memset(dis, 63, 100);
dis[0][0] = 0;
}
bool find()
{
queue<point> q;
q.push(point(0, 0));
map[0][0] = 1;
while (!q.empty())
{
point p = q.front();
q.pop();
if (p.x == 4 && p.y == 4)
return true;
for (int i = 0; i < 4; i++)
{
int newX = p.x + dx[i];
int newY = p.y + dy[i];
if (map[newX][newY] == 0 &&
newX >= 0 && newX <= 4 &&
newY >= 0 && newY <= 4)
{
q.push(point(newX, newY));
map[newX][newY] = 1;
dis[newX][newY] = 1 + dis[p.x][p.y];
}
}
}
return false;
}
void print()
{
stack<point> route;
route.push(point(4, 4));
point p = route.top();
while (1)
{
for (int i = 0; i < 4; i++)
{
int newX = p.x + dx[i];
int newY = p.y + dy[i];
if (newX >= 0 && newX <= 4 &&
newY >= 0 && newY <= 4 &&
dis[newX][newY] == dis[p.x][p.y] - 1)
{
point newPoint(newX, newY);
route.push(newPoint);
p = newPoint;
if (newX == 0 && newY == 0)
{
while (!route.empty())
{
point thePoint = route.top();
route.pop();
cout << '(' << thePoint.x << ',' << ' ' << thePoint.y << ')' << endl;
}
return;
}
}
}
}
}
int main()
{
input();
if(find())
print();
}
效果如图: