题意
东东有一张地图,想通过地图找到妹纸。地图显示,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)
思路
总结
代码
#include<cstdio>
#include<iostream>
#include<string>
#include<cmath>
#include<cstdlib>
#include<queue>
using namespace std;
struct point
{
int x,
y;
};
int map[5][5];
point route[5][5];
const int x2[4] = { +1,-1,0,0 };
const int y2[4] = { 0,0,+1,-1 };
void r(point);
int main()
{
queue<point> q;
for (int j = 0; j < 5; j++)
for (int i = 0; i < 5; i++)
cin >> map[j][i];
point p1;
p1.x = 0;
p1.y = 0;
q.push(p1);
while (!q.empty())
{
point head = q.front(), temp;
q.pop();
for (int i = 0; i < 4; i++)
{
temp.x = x2[i] + head.x;
temp.y = y2[i] + head.y;
if (temp.x < 0 || temp.y < 0 ||temp.x > 4 || temp.y > 4|| map[temp.x][temp.y] == 1 || map[temp.x][temp.y] == 2)
continue;
map[temp.x][temp.y] = 2;
route[temp.x][temp.y] = head;
q.push(temp);
}
}
point p2;
p2.x = 4;
p2.y = 4;
r(p2);
return 0;
}
void r(point p)
{
if (p.x != 0 || p.y != 0)
r(route[p.x][p.y]);
if(p.x!=4||p.y!=4)
printf("(%d, %d)\n", p.x, p.y);
else
printf("(%d, %d)", p.x, p.y);
return;
}