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,
};
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)
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 }
原文地址:http://www.cnblogs.com/zzy9669/p/3855114.html