迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 12134 | Accepted: 7277 |
Description 定义一个二维数组:
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)
思路:定义一个数组dis用来表示(0,0)点到当前点要做几步,用BFS走一遍,然后从(4,4)点往回走,先把(4,4)入栈,令dis<4,4>为a【从(0,0)到(4,4)要走的步数】,令当前点为(4,4),①则走到则当前点的上一点需要的步数为a-1,②遍历当前点的周围四方向【不越界】,③找出该点入栈,④把该点作为当前点,重复上述①②③④,直到回到(0,0);
本题用DFS和BFS均可
已Accept代码【c++提交】
BFS☟
0MS 144K
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
using namespace std;
int map[6][6];
int dis[6][6];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
typedef struct node{
int x, y;
node() {}
node(int x, int y) : x(x), y(y) {}
}node;
void BFS() {
queue <node> Q;
memset(dis, 100, sizeof(dis));
Q.push(node(0, 0));
dis[0][0] = 0;
while(!Q.empty()) {
node k = Q.front();
Q.pop();
int x = k.x;
int y = k.y;
for(int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx < 0 || nx >= 5 || ny < 0 || ny >= 5 || map[nx][ny] == 1)
continue;
if(dis[nx][ny] > dis[x][y] + 1) {
dis[nx][ny] = dis[x][y] + 1;
Q.push(node(nx, ny));
}
}
}
stack <node> S;
int x = 4, y = 4;
S.push(node(x, y));
while(1) {
if(x == 0 && y == 0)
break;
for(int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx < 0 || nx >= 5 || ny < 0 || ny >= 5)
continue;
if(dis[x][y] == dis[nx][ny] + 1) {
x = nx;
y = ny;
S.push(node(x, y));
}
}
}
while(!S.empty()) {
node a = S.top();
S.pop();
printf("(%d, %d)\n", a.x, a.y);
}
}
int main() {
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
scanf("%d", &map[i][j]);
BFS();
return 0;
}
DFS☟
0MS 164K
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
int map[6][6];
int dis[7][7];
int n[18];
int m[18];
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
void dfs(int sc, int sr, int total) {
if(sc < 1 || sc > 5 || sr < 1 || sr > 5)
return ;
if(map[sc][sr] == 1)
return ;
if(total + 1 >= dis[sc][sr])
return ;
dis[sc][sr] = total + 1 ;
map[sc][sr] = 1;
for(int i = 0; i < 4; i++) {
int nx = sc + dx[i];
int ny = sr + dy[i];
dfs(nx, ny, dis[sc][sr]);
}
map[sc][sr] = 0;
return ;
}
void Scanf_a() {
memset(dis, 0x3f, sizeof(dis));
for(int i = 1; i < 6; i++)
for(int j = 1; j < 6; j++)
scanf("%d", &map[i][j]);
}
void Printf_a() {
int x = 5, y = 5, q = 0;
int current = dis[x][y];
n[q] = x;
m[q++] = y;
while(x != 1 || y !=1) {
for(int i = 0; i < 4; i++) {
if(dis[x + dx[i]][y + dy[i]] == current - 1) {
x = x + dx[i];
y = y + dy[i];
n[q] = x;
m[q++] = y;
current--;
}
}
}
for(int j = dis[5][5] - 1; j >= 0; j--)
printf("(%d, %d)\n", n[j] - 1, m[j] - 1);
}
int main(){
Scanf_a();
dfs(1, 1, 0);
Printf_a();
system("pause");
return 0;
}