B:最简单的啦
Problem Description:
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)
One way to solve the problem:
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
struct Maze{
int x, y;
}A;
struct Par{
int x, y;
};
int map[6][6];
int visited[6][6];
Par par[6][6];//用来保存父节点的数组
int dir[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
void Init()
{
memset(par, -1, sizeof(par));
memset(visited, 0, sizeof(visited));
A.x = 0; A.y = 0;
visited[0][0] = 1;
par[0][0].x = 0; par[0][0].y = 0;
}
void BFS()
{
queue<Maze>q;
q.push(A);
while(!q.empty())
{
Maze u = q.front(); q.pop();
if(u.x == 4 && u.y == 4)
{
return;
}
for(int i=0; i<4; i++)
{
int dx = u.x + dir[i][0];
int dy = u.y + dir[i][1];
if(dx < 0 || dx > 4 || dy < 0 || dy > 4 || map[dx][dy] || visited[dx][dy])
continue;
visited[dx][dy] = 1;
Maze v;
v.x = dx; v.y = dy;
q.push(v);
par[dx][dy].x = u.x; par[dx][dy].y = u.y;//保存父节点
}
}
}
void DFS(int x, int y)
{
if(x == 0 && y == 0) return;
DFS(par[x][y].x, par[x][y].y);
printf("(%d, %d)\n",par[x][y].x, par[x][y].y);
}
int main()
{
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
scanf("%d", &map[i][j]);
}
}
Init();
BFS();
DFS(4,4);
printf("(4, 4)\n");
return 0;
}