题目
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 20975 | Accepted: 12281 |
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
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, };
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
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)
思路
BFS经典应用题。。。
代码
#include <iostream>
#include <stack>
#include <queue>
#include <utility>
#include <cstring>
using namespace std;
typedef pair<int, int > P;
#define MAX_N 6
P G, S;
int dx[] = {-1, 0, 0, 1};
int dy[] = { 0, 1,-1, 0};
int maze[MAX_N][MAX_N];
P parents[MAX_N][MAX_N];
bool used[MAX_N][MAX_N];
int NX, NY;
void bfs();
void solve();
int main()
{
NX = NY = 4;
S = P(0, 0); G = P(4, 4);
for (int i = 0; i <= NX; i++) {
for (int j = 0; j <= NY; j++) {
cin >> maze[i][j];
}
}
solve();
return 0;
}
void bfs() {
queue<P> que;
memset(parents, -1, sizeof(parents));
memset(used, false, sizeof(used));
que.push(make_pair(S.first, S.second) );
used[S.first][S.second] = true;
while (!que.empty()) {
P v = que.front(); que.pop();
if (v == G) break;
for (int i = 0; i < 4; i++) {
int nx = v.first + dx[i], ny = v.second + dy[i];
if (nx >= 0 && nx <= NX && ny >= 0 && ny <= NY && !used[nx][ny] && maze[nx][ny] == 0) {
que.push(make_pair(nx, ny) );
parents[nx][ny] = v;
used[nx][ny] = true;
}
}
}
}
void solve() {
bfs();
// cout << "parents: " << endl;
// for (int i = 0; i <= 4; i++) {
// for (int j = 0; j <= 4; j++) {
// cout.width(2);
// cout << "(" << parents[i][j].first << ",";
// cout.width(2);
// cout << parents[i][j].second << ") " << " ";
// }
// cout << endl;
// }
P v = G;
stack<P> path;
path.push(v);
int nx = v.first, ny = v.second;
while(parents[v.first][v.second] != P(-1,-1)) {
path.push(parents[v.first][v.second]);
v = parents[v.first][v.second];
}
while (!path.empty()) {
P vs = path.top(); path.pop();
cout << "(" << vs.first << ", " << vs.second << ")" << endl;
}
}