Subject description:
Links: https://www.nowcoder.com/questionTerminal/e3fc4f8094964a589735d640424b6a47
Source: cattle off network
assume an explorer trapped in underground labyrinths, from the current position to find a path leading to the exit of the maze. Maze can be a two-dimensional matrix composed of some part of the wall, and some part of the road. Among the maze of the road there are some doors, every door there is a matching key somewhere in the maze, only to get the key to open the door. Please design an algorithm to help explorers to find the shortest path out of poverty. As described above, through the labyrinth is a two-dimensional matrix, meaning the value of each element of the wall as 0-, 1- path explorer starting position 2-, 3- labyrinth outlet, capital letters - Door , lowercase letters - correspondence door initials stand for the key
Analysis of ideas:
Bfs and uses state of compression.
Code:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<iostream> 4 #include<vector> 5 #include<algorithm> 6 #include<queue> 7 #include<string.h> 8 using namespace std; 9 10 int n,m,sx,sy,ex,ey; 11 char g[1024][1024]; 12 int use[120][120][1400]; 13 int dx[]={0,0,1,-1}; 14 int dy[]={1,-1,0,0}; 15 struct node 16 { 17 int x,y,k; 18 }; 19 20 int bfs() 21 { 22 memset(use,0xff,sizeof(use)); 23 queue<node>q; 24 node t; 25 t.x=sx; 26 t.y=sy; 27 t.k=0; 28 use[t.x][t.y][t.k]=0; 29 q.push(t); 30 while(!q.empty()) 31 { 32 t = q.front(); 33 q.pop(); 34 //printf("%d %d %d %d\n",t.x,t.y,t.k,use[t.x][t.y][t.k]); 35 if(t.x==ex&&t.y==ey) return use[t.x][t.y][t.k]; 36 for(int i=0;i<4;i++)//上下左右 37 { 38 K Node; // are about to go up at 39 KX = TX + DX [I]; 40 KY = TY + Dy [I]; 41 is KK = TK; 42 is IF (KX < 0 || KX> = n-KY || < 0 || KY> || G = m [KX] [KY] == ' 0 ' ) Continue ; // directly into the next cycle 43 is IF (G [KX] [KY]> = ' A ' && G [KX ] [KY] <= ' Z ' ) 44 is { 45 KK KK = | ( . 1<< (G [KX] [KY] - ' A ' )); // go pick up the key point key 46 is } 47 IF (G [KX] [KY]> = ' A ' && G [KX] [KY] <= ' the Z ' ) 48 { 49 int P & KK = ( . 1 << (G [KX] [KY] - ' A ' )); // far as the door of the matching key 50 IF (P == 0 ) Continue ; // no direct access to the next cycle key 51 is } 52 is IF (use [KX] [KY] [KK] == - . 1use || [KX] [KY] [KK]> use [TX] [TY] [TK] + . 1 ) // first condition ensures that BFS, the second condition ensures that does not go wall 53 is { 54 is use [KX] [KY] [KK] use = [TX] [TY] [TK] + . 1 ; 55 q.push (K); 56 is } 57 is } 58 } 59 return - . 1 ; 60 } 61 is 62 is int main () 63 is { 64 Scanf ( " % D% D " , & n-, & m); 65 for ( int I =0; i<n; i++) 66 { 67 scanf("%s",g[i]); 68 for(int j=0; j<m; j++) 69 { 70 if(g[i][j] == '2') 71 { 72 sx = i; 73 sy = j; 74 } 75 if(g[i][j] == '3') 76 { 77 ex = i; 78 ey = j; 79 } 80 } 81 } 82 printf("%d\n",bfs()); 83 return 0; 84 }