迷宫问题 POJ

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)

思路:BFS并储存路径
AC Code:
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<queue> 
#include<cstring>
using namespace std;
#define MAX_N 100
int INF = 0x3f3f3f3f;
char maze[MAX_N][MAX_N];
int dis[MAX_N][MAX_N];
bool vis[MAX_N][MAX_N];
string s;
int dir[4][2] = {1, 0, 0, -1, 0, 1, -1, 0};
char print[5] = "DLRU";
int N, M;

void BFS (int sx, int sy, int fx, int fy) {
    queue<pair<int, int>> q;
    q.push(make_pair(sx, sy));
    dis[sx][sy] = 0;
    vis[sx][sy] = true;
    while (!q.empty()) {
        int x = q.front() .first;
        int y = q.front().second;
        q.pop();
        for (int i = 0; i < 4; i++) {
            int nx = x + dir[i][0];
            int ny = y + dir[i][1];
            if (nx >= 0 && nx <= N && ny >= 0 && ny <= M && maze[nx][ny] == '0' && vis[nx][ny] == false && dis[nx][ny] == INF) {
                dis[nx][ny] = dis[x][y] + 1;
                vis[nx][ny] = true;
                q.push(make_pair(nx, ny)); 
            }
        }
    }
}
void BFSprint (int sx, int sy) {
    queue<pair<int, int>> q;
    q.push(make_pair(sx,sy));
    printf("(%d, %d)
", sx, sy);
    while (!q.empty()) {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        for (int i = 0; i < 4; i++){
            int nx = x + dir[i][0];
            int ny = y + dir[i][1];
            if (nx >= 0 && nx < N && ny >= 0 && ny <= M && dis[nx][ny] + 1 == dis[x][y]){
                printf("(%d, %d)
", nx, ny);
                q.push(make_pair(nx, ny));
                break;
            }
        }
    }
}
int main(){
    memset(dis,INF,sizeof(dis));
    N = M = 5;
    for (int i = 0; i < N; i++) 
        for (int j = 0; j < M; j++)
            cin >> maze[i][j];
    BFS(N - 1, M - 1, 0, 0);    
    BFSprint(0, 0);
}
  人生不如意的时候,是上帝给的长假,这个时候应该好好享受假期。
  突然有一天假期结束,时来运转,人生才是真正开始了。
原文地址:https://www.cnblogs.com/astonc/p/9900486.html