POJ 3984 迷宮問題【迷宮最短路徑 bfs】

POJ 3984 迷宮問題【迷宮最短路徑 bfs】

題目鏈接 http://poj.org/problem?id=3984

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXL = 10; // 矩陣最大寬度
char maze[MAXL][MAXL]; // 迷宮
bool vis[MAXL][MAXL]; // 訪問標記
int n, m; // 迷宮的長和寬
int dirx[4] = {0, 1, 0, -1};
int diry[4] = {1, 0, -1, 0}; // 移動方向
typedef struct point{
    int x, y;
}P; // 座標
P path[MAXL*MAXL]; // 路徑隊列
int pre[MAXL*MAXL]; // 記錄父結點
P start, goal; // 起點 終點
P current, next; // 當前座標 下一步的座標

void Output(){
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            printf("%d\t", maze[i][j]);
        }
        printf("\n");
    }
}

void Input(){
    memset(maze, 0, sizeof(maze));
    memset(vis, 0, sizeof(vis));
    n = 5;
    m = 5;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            scanf("%c", &maze[i][j]);
            maze[i][j] -= '0';
            if(j != n-1) getchar(); // 輸入空格
        }
        getchar(); // 輸入回車
    }
    //Output();
}

void Print(int pos){
    if(pos == 0){ // 輸出起點
        printf("(%d, %d)\n", path[pos].x, path[pos].y);
    }
    else{
        int pointer;
        pointer = pre[pos]; // 父結點在路徑中的位置
        Print(pointer);
        printf("(%d, %d)\n", path[pos].x, path[pos].y);
    }
}

void bfs(){
    start.x = 0;
    start.y = 0;
    goal.x = n-1;
    goal.y = m-1;
    int head, tail; // 隊頭 隊尾
    int x, y, xx, yy; // x,y是當前座標 xx,yy是下一步的座標
    head = 0;
    path[0].x = start.x;
    path[0].y = start.y;
    pre[0] = -1;
    vis[start.x][start.y] = true;
    tail = 1; // 起點入隊
    while(head < tail){ // 如果隊列不爲空
        x = path[head].x;
        y = path[head].y;
        if(x == goal.x && y == goal.y){
            Print(head); // 走到終點 打印最短路徑
            return;
        }
        for(int i = 0; i < 4; i++){
            xx = x + dirx[i];
            yy = y + diry[i];
            if(xx >= 0 && xx < n && yy >= 0 && yy < m && maze[xx][yy] == 0 && !vis[xx][yy]){
                vis[xx][yy] = true;
                path[tail].x = xx;
                path[tail].y = yy;
                pre[tail] = head;
                tail++; // 當前座標入隊
            }
        }
        head++; // 四個方向都走過後元素出隊
    }
}

int main(){
    Input();
    bfs();
    return 0;
}

還有一個使用queue的版本,來自網絡:
http://m.blog.csdn.net/blog/yzj577/37997073

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章