迷宮問題
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7635 | Accepted: 4474 |
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)
Source
廣搜,入門題。
題意:
給你一個5*5的迷宮,0代表通路,1代表牆,找到從迷宮左上角到達右下角的最短路徑,並輸出路徑。
思路:
這道題是一道比較簡單的廣搜題目,為什么是廣搜?因為題意是要找最短路徑,這類題基本上就是用廣搜。但是與其他直接輸出最短路徑的步數的不同,這道題要輸出的是最短路徑,是要輸出這個路徑,所以就要考慮狀態了,每一個狀態都應該存儲到達這個狀態的路徑。其他就沒什么好說的了,總體上是一道較為簡單的廣搜入門題。
代碼:
1 #include <iostream>
2 #include <stdio.h>
3 #include <string.h>
4 #include <queue>
5 using namespace std; 6
7 bool isw[5][5]; 8 int a[5][5]; 9 int dx[4] = {0,1,0,-1}; 10 int dy[4] = {1,0,-1,0}; 11
12 struct Node{ 13 int x; 14 int y; 15 int s; 16 short l[30]; 17 }; 18
19 bool judge(int x,int y) 20 { 21 if(x<0 || x>=5 || y<0 || y>=5) 22 return true; 23 if(isw[x][y]) 24 return true; 25 if(a[x][y]==1) 26 return true; 27 return false; 28 } 29
30 Node bfs() 31 { 32 queue <Node> q; 33 Node cur,next; 34 cur.x = 0; 35 cur.y = 0; 36 cur.s = 0; 37 isw[cur.x][cur.y] = true; 38 q.push(cur); 39 while(!q.empty()){ 40 cur = q.front(); 41 q.pop(); 42 if(cur.x==4 && cur.y==4) 43 return cur; 44 int i,nx,ny; 45 for(i=0;i<4;i++){ 46 nx = cur.x + dx[i]; 47 ny = cur.y + dy[i]; 48 if(judge(nx,ny)) 49 continue; 50 //可以走
51 next = cur; 52 next.x = nx; 53 next.y = ny; 54 next.s = cur.s + 1; 55 next.l[cur.s] = i; 56 q.push(next); 57 } 58 } 59 return cur; 60 } 61
62
63 int main() 64 { 65 int i,j; 66 for(i=0;i<5;i++){ //讀入迷宮
67 for(j=0;j<5;j++){ 68 scanf("%d",&a[i][j]); 69 } 70 } 71 memset(isw,0,sizeof(isw)); 72 Node ans = bfs(); 73 int x,y; 74 x = 0,y = 0; 75 for(i=0;i<=ans.s;i++){ 76 printf("(%d, %d)\n",x,y); 77 x+=dx[ans.l[i]]; 78 y+=dy[ans.l[i]]; 79 } 80 return 0; 81 }
Freecode : www.cnblogs.com/yym2013