# [置顶] poj 3984 迷宫问题【BFS && DFS】【简单】

109人阅读 评论(0)

﻿﻿

 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,
};

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☟

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;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：17149次
• 积分：995
• 等级：
• 排名：千里之外
• 原创：84篇
• 转载：3篇
• 译文：0篇
• 评论：0条
阅读排行
文章分类