POJ 3984迷宮問題(BFS+打印)

在這裏插入圖片描述

加了打印路徑,從後往前打。
AC代碼:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int vis[10][10], Map[10][10];
int head, tot;
int dx[4] = { 0, 1, -1, 0 };
int dx[4] = { 0, 1, -1, 0 };
int dy[4] = { 1, 0, 0, -1 };
struct node {
    int x;
    int y;
    int pre;
} num[1100];
void print(int n){
    if (num[n].pre != -1) {
        print(num[n].pre);
        printf("(%d, %d)\n", num[n].x, num[n].y);
    }
    return;
}
void bfs(){
    //注意區分head和tot,前一個表示每一步,後一個表示有多少種嘗試
    head = 0;
    tot = 0;
    while (head < tot) {
        for (int i = 0; i < 4; i++) {
            int m = num[head].x + dx[i];
            int n = num[head].y + dy[i];
            if (m >= 5 || n >= 5 || m < 0 || n < 0 || Map[m][n] == 1)
                continue;
            Map[m][n] = 1;
            num[tot].x = m;
            num[tot].y = n;
            num[tot].pre = head;
            tot++;
            if (m == 4 && n == 4)
                print(head);
        }
        head++;
    }
}
int main() {
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++)
            scanf("%d", &Map[i][j]);
    }
    printf("(0, 0)\n");
    bfs();    
    printf("(4, 4)\n");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章