Topic link: Click to open the link
Note: If we reach a grid where a trap is located, the trap will be triggered automatically and disappear immediately after triggering.
If you go to the i-th organ and step on any of the organs after i, you will fail.
Born in any institution except the first institution, fail
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; const int N = 110; char a[N][N]; // store the map int vis[N][N]; // vis[i][j] = 1 if the point has been traversed, 0 has not been traversed int mis[N][N]; // mis[i][j] = 1 This point will trigger the trap in the future, so it cannot be traversed now typedef struct point { int x, y, step; }P; int n, m, k; // 8 directions int road[8][2] = {-1,-1, -1,0, -1,1, 0,-1, 0, 1, 1,-1, 1,0, 1,1}; queue <P> Q; P score[N]; // Determine whether the item is outside the picture bool judge(P tem) { if(tem.x < 0 || tem.x >= n || tem.y < 0 || tem.y >= m) return false; return true; } // Determine whether it is possible to walk diagonally to the tem bool wtwalk(int i, P tem) { P tem1, tem2; has1 = has; has2 = has; if(i == 0) { tem1.y ++; tem2.x++; } else if(i == 2) { item1.y --; tem2.x++; } else if(i == 5) { tem1.x -; tem2.y ++; } else { tem1.x--; item2.y--; } if(a[tem1.x][tem1.y] == '#' && a[tem2.x][tem2.y] == '#') return false; return true; } // bfs Sta is the starting point, End is the end point // If the end point can be reached, return the number of steps // if not return -1 int bfs(P Sta, P End) { memset(vis, 0, sizeof(vis)); vis [Sta.x] [Sta.y] = 1; while(!Q.empty()) Q.pop(); Q.push( Sta ); P now, tem; while( !Q.empty() ) { now = Q.front(); if(now.x == End.x && now.y == End.y) { return now.step; } Q.pop(); for(int i=0; i<8; i++) { tem.x = now.x + road[i][0]; tem.y = now.y + road[i][1]; if( vis[tem.x][tem.y] || mis[tem.x][tem.y] || a[tem.x][tem.y] == '#' || !judge(tem ) ) continue; if(0 == i || 2 == i || 5 == i || 7 == i) { if(!wtwalk(i, tem)) continue; } // cout << tem.x+1 << " " << tem.y+1 << endl; force[tem.x][tem.y] = 1; tem.step = now.step+1; Q.push( tem ); } } return -1; } intmain() { int T; cin >> T; for(int t=1; t<=T; t++) { cin >> n >> m >> k; memset(mis, 0, sizeof(mis)); for(int i=0; i<n; i++) cin >> a[i]; P now; cin >> now.x >> now.y; now.x --, now.y --; now.step = 0; int years = 0; for(int i=1; i<=k; i++) { cin >> score[i].x >> score[i].y; score[i].x --; score[i].y --; if(score[i].x == now.x && score[i].y == now.y && i!=1){ years = -1; } if(i != 1) { mis[score[i].x][score[i].y] = 1; } } if(ans == -1) { cout << "-1" << endl; continue; } for(int i=1; i<=k; i++) { mis[score[i].x][score[i].y] = 0; int temp = bfs(now, score[i]); if(temp >= 0) { score[i].step = 0; now = score[i]; years += temp; } else { years = -1; break; } } cout << ans << endl; } return 0; }