1. 程式人生 > >POJ-3984

POJ-3984

這題是bfs的基礎性題目,但是基礎才顯得很重要。

題目中的要求是輸出每一個我們走過的點,所以我們每次記錄下它的上一個節點是誰就行了。

但是我們因此就不能再使用隊列了,我們開闢一個一維陣列就行了,因為迷宮的大小是5*5的,所以我們直接開一個一維陣列,然後模擬一下佇列的進出就行了。

這個題比較坑的一點是它的輸出圓括號裡面,逗號後面有個空格,一定要輸出,不然它會說,你的答案几乎正確,但是格式不對。

#include <iostream>
#include <cstring>
using namespace std;
struct Road {
    int r,c;
    int f;
};
const int MAXN=1000;
Road q[MAXN];
bool maze[5][5];
bool visited[5][5];
int head=0,tail=0;
int d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};

void bfs()
{
	while (head<tail) {
        Road front=q[head];
        if (front.c==4&&front.r==4) {
            break;
        }
        for (int i=0;i<4;i++) {
            Road last;
            last.r=front.r+d[i][0];
            last.c=front.c+d[i][1];
            if (last.r>=0&&last.r<=4&&last.c<=4&&last.c>=0) {
                if (!visited[last.r][last.c]&&!maze[last.r][last.c]) {
                    last.f=head; 
                    q[tail++]=last;
                    visited[last.r][last.c]=1;
                }
            }
        }
        head++;//head 在此加加,不會出現死迴圈
    }
}

int main()
{
    int path[30];
    for (int i=0;i<5;i++) {
        for (int j=0;j<5;j++) {
            cin>>maze[i][j];
        }
    }
    memset(visited,0,sizeof(visited));
	Road a={0,0,-1};
    q[tail++]=a;
    visited[0][0]=1;
    bfs();
    int i=0;
    while (q[head].f>=0) {
        path[i++]=q[head].f;
        head=path[i-1];
    }
    for (int j=i-1;j>=0;j--) {
        cout<<"("<<q[path[j]].r<<", "<<q[path[j]].c<<")"<<endl;
    }
    cout<<"("<<4<<", "<<4<<")"<<endl;
    return 0;
}