標籤:des style blog color os 資料
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
一個5 × 5的二維數組,表示一個迷宮。資料保證有唯一解。
Output
左上方到右下角的最短路徑,格式如範例所示。
Sample Input
0 1 0 0 00 1 0 1 00 0 0 0 00 1 1 1 00 0 0 1 0
Sample Output
(0, 0)(1, 0)(2, 0)(2, 1)(2, 2)(2, 3)(2, 4)(3, 4)(4, 4)
BFS•我們在bfs的時候,需要邊bfs邊記錄路徑•具體的來說,就是bfs到下一個點的時候,要記錄它是通過誰走到這個點的•輸出的時候要從終點反向尋找路徑,用數組儲存起來•最後將記錄結果的數組反向輸出
1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 5 const int dx[]={0, 1 ,0 ,-1} ; 6 const int dy[]={1, 0 ,-1 ,0} ; 7 int a[5][5] ,vis[5][5], fa[25], ans[25]; 8 9 int main()10 {11 for(int i=0;i<5;i++)12 for(int j=0;j<5;j++)13 cin>>a[i][j];14 queue<int>Q;15 Q.push(0) ;16 vis[0][0] = 1 ;17 while(!Q.empty()){18 int u = Q.front(); Q.pop() ;19 int x=u/5 , y = u%5;20 for(int d=0; d<4; d++){21 int nx = x + dx[d] , ny = y + dy[d];22 if(nx<0 || nx>=5 || ny<0 || ny>=5 || vis[nx][ny] || a[nx][ny]) continue ;23 int v = nx * 5 + ny ;24 vis[nx][ny] = 1 , fa[v] = u ;25 Q.push(v);26 }27 }28 int p = 24 , top = 0 ;29 while(true){30 ans[top++] = p ;31 if(p == 0) break;32 p = fa[p];33 }34 while(top>0) {35 --top ;36 cout<<"("<<ans[top]/5<<", "<<ans[top]%5<<")"<<endl;37 }38 return 0;39 }
另解:DFS
1 #include<stdio.h> 2 #include<string.h> 3 4 int a[7][7], c[7][7], minn; 5 int b[5][5]; 6 7 int moves[4][2]={{0,-1}, {-1,0}, {0,1}, {1,0}}; 8 void display() 9 {10 int i, j;11 for(i = 0; i < 5; i++)12 for(j = 0; j < 5; j++)13 if(c[i][j] == 1)14 printf("(%d, %d)\n", i, j);15 }16 17 void change()18 {19 int i, j;20 for(i = 0; i < 5; i++)21 for(j = 0; j < 5; j++)22 c[i][j] = b[i][j];23 }24 25 void dfs(int i,int j,int count)26 {27 int k;28 if(i == 4 && j == 4){29 if(count<minn){30 minn = count;31 change();32 }33 return;34 }35 for(k = 0; k < 4; k++){36 int x = i + moves[k][0];37 int y = j + moves[k][1];38 if(x >= 0 && x < 5 && y >= 0 && y < 5 && a[x][y]==0){39 b[i][j] = 1;40 a[i][j] = 1;41 count++;42 dfs(x, y, count+1);43 count--;44 b[i][j]=0;45 a[i][j]=0;46 }47 }48 }49 50 int main()51 {52 int i, j;53 minn = 25;54 memset(b, 0, sizeof(b));55 memset(c, 0, sizeof(c));56 for(i = 0; i < 5; i++)57 for(j = 0; j < 5; j++)58 scanf("%d", &a[i][j]);59 b[4][4] = 1;60 dfs(0, 0, 1);61 display();62 return 0;63 }