迷宮問題 (廣搜)
阿新 • • 發佈:2018-11-24
定義一個二維陣列:
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)
這是一道典型的廣搜題,思路就不說了,路徑儲存值得學習,我採用指標遞迴的方式輸出路徑
void output(node* s)
{
if(s==NULL) return;
output(s->last);
printf("(%d, %d)\n",s->x,s->y);
}
我個人認為這種遞迴的方式用起來比較爽,但是自己不擅長 啊哈哈哈哈~~~
#include<iostream> #include<cstdio> #include<cstdlib> #include<queue> using namespace std; struct node{ int x,y; int step; node* last; }; int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}}; int map[10][10]; int book[10][10]={0}; node* bfs() { node* e; e=(node*)malloc(sizeof(node)); queue<node*> q; e->x=0; e->y=0; e->step=0; e->last=NULL; q.push(e); while(!q.empty()) { e=q.front(); q.pop(); if(e->x==4&&e->y==4) return e; for(int i=0;i<4;i++) { int tx=e->x+next[i][0]; int ty=e->y+next[i][1]; if(tx<0||tx>4||ty<0||ty>4||map[tx][ty]||book[tx][ty]) continue; book[tx][ty]=1; node* p; p=(node*)malloc(sizeof(node)); p->x=tx; p->y=ty; p->step=e->step+1; p->last=e; q.push(p); } } return NULL; } void output(node* s) { if(s==NULL) return; output(s->last); printf("(%d, %d)\n",s->x,s->y); } int main() { for(int i=0;i<5;i++) for(int j=0;j<5;j++) cin>>map[i][j]; book[0][0]=1; output(bfs()); return 0; }