迷宮問題
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 20816 | Accepted: 12193 |
Description
定義一個二維數組:
它表示一個迷宮,其中的1表示牆壁,0表示可以走的路,只能橫着走或豎着走,不能斜着走,要求編程序找出從左上角到右下角的最短路線。
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)
這道題是一道比較簡單的廣搜題目,為什么是廣搜?因為題意是要找最短路徑,這類題基本上就是用廣搜。
但是與其他直接輸出最短路徑的步數的不同,這道題要輸出的是最短路徑,是要輸出這個路徑,所以就要考慮狀態了,
每一個狀態都應該存儲到達這個狀態的路徑。其他就沒什么好說的了,總體上是一道較為簡單的廣搜入門題。
#include "cstdio" #include "iostream" #include "queue" using namespace std; int a[5][5]; bool visit[5][5]; int dx[4]={1,-1,0,0},dy[4]={0,0,1,-1}; struct Node{ int x,y; int s;///路徑長度 int l[30];///每走一步的方向 };///通過記錄方向來記錄路徑 bool judge(int x,int y) { if(x<0||x>=5||y<0||y>=5) return true; if(visit[x][y]) return true; if(a[x][y]==1) return true; return false; } Node& bfs() { queue<Node> que; Node cur,next; cur.x=0;cur.y=0;cur.s=0; visit[0][0]=1; que.push(cur); while(que.size()) { cur=que.front(); que.pop(); if(cur.x==4&&cur.y==4) return cur; int i,nx,ny; for(i=0;i<4;i++) { nx=cur.x+dx[i]; ny=cur.y+dy[i]; if(judge(nx,ny)) continue; next=cur; next.x=nx; next.y=ny; next.s=cur.s+1; next.l[cur.s]=i; visit[nx][ny]=1; que.push(next); } } return cur; } int main() { for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { scanf("%d",&a[i][j]); } } Node ans=bfs(); printf("(0, 0)\n"); int x=0,y=0; for(int i=0;i<ans.s;i++) { x+=dx[ans.l[i]]; y+=dy[ans.l[i]]; printf("(%d, %d)\n",x,y); } return 0; }