繼續學習搜索,前幾天寫了該題的DFS解法,這次寫了一個BFS。方法是自己模擬了一個隊列。
此題關鍵點是模擬隊列,用front和rare模擬出入隊,用下標pre模擬指針,指向上一個節點。例如(4,4)爲最後一個點,pre指向15,即上一個點的位置是15,遞歸輸出。此題切入點是用什麼結構暫存搜索結果,例如棧,隊列等等
如果不是很理解的話認真看一遍代碼,每一行都真正弄懂就會理解了。如果對BFS隊列有問題,或者搜索方面還需要入門學習的,下面給一個ACM搜索課件
ACM搜索課件 這個是天津大學的acm培訓課件,轉發請註明出處。關於BFS隊列的操作內容在PPT第53頁。
DFS解法鏈接→ POJ 3984 迷宮問題 DFS解法
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10966 | Accepted: 6546 |
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
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)
題目鏈接→POJ 3984 迷宮問題
下面是用BFS實現的AC代碼
#include<iostream>
#include <cstdio>
using namespace std;
int map[5][5];
int dx[4]={1,-1,0,0};
int dy[4]={0,0,-1,1};
int front=0,rear=1;
struct node{
int x,y,pre;
}q[100];
void print(int i)//輸出過程
{
if(q[i].pre!=-1)
{
print(q[i].pre);
printf("(%d, %d)\n",q[i].x,q[i].y);
}
}
void bfs(int x,int y)
{
q[front].x=x;
q[front].y=y;
q[front].pre=-1; //pre記錄前一個結點的狀態,用於記錄路徑
while(front<rear)//當隊列不空
{
for(int i=0;i<4;i++) //搜索可達的路徑(向上下左右走)
{
int a=dx[i]+q[front].x;
int b=dy[i]+q[front].y;
if(a<0||a>=5||b<0||b>=5||map[a][b]) //如果超出迷宮邊界或者不可行
continue;
else
{
map[a][b]=1; //走過的路標記1
q[rear].x=a;
q[rear].y=b;
q[rear].pre=front;
rear++; //入隊
}
if(a==4 && b==4) //當a與b滿足條件時,尋找pre的關係輸出整個隊列que
print(front);
}
front++; //出隊
}
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>map[i][j];
cout<<"(0, 0)"<<endl;
bfs(0, 0);
cout<<"(4, 4)"<<endl;
return 0;
}