把点抽出来 跑个最短路就好啦。
1 #include<bits/stdc++.h> 2 #define LL long long 3 #define pii pair<int,int> 4 #define mk make_pair 5 #define fi first 6 #define se second 7 using namespace std; 8 9 const int N=300+7; 10 const int M=1e5+7; 11 const int inf=0x3f3f3f3f; 12 const LL INF=0x3f3f3f3f3f3f3f3f; 13 const int mod=1e9+7; 14 15 int n, m, q, idx, S, T, d[N * N], hs[N][N], dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1}; 16 char s[N][N]; 17 18 vector<pii> edge[N * N]; 19 20 21 int Dj(int S, int T) { 22 priority_queue<pii, vector<pii>, greater<pii> > que; 23 d[S] = 0; que.push(mk(0, S)); 24 while(!que.empty()) { 25 pii u = que.top(); 26 que.pop(); 27 if(u.fi < d[u.se]) continue; 28 if(u.se == T) { 29 return u.fi; 30 } 31 for(pii v : edge[u.se]) { 32 if(d[u.se] + v.fi < d[v.se]) { 33 d[v.se] = d[u.se] + v.fi; 34 que.push(mk(d[v.se], v.se)); 35 } 36 } 37 } 38 return -1; 39 } 40 void init() { 41 idx = 0; 42 for(int i = 0; i <= n * n + 10; i++) 43 edge[i].clear(), d[i] = inf; 44 } 45 46 bool check(int x, int y) { 47 if(x > n || x < 1) return false; 48 if(y > m || y < 1) return false; 49 if(s[x][y] == '#') return false; 50 return true; 51 } 52 int main() { 53 while(scanf("%d%d%d", &n, &m, &q) != EOF) { 54 init(); 55 for(int i = 1; i <= n; i++) 56 scanf("%s", s[i] + 1); 57 for(int i = 1; i <= n; i++) { 58 for(int j = 1; j <= m; j++) { 59 hs[i][j] = ++idx; 60 if(s[i][j] == 'S') S = idx; 61 if(s[i][j] == 'T') T = idx; 62 } 63 } 64 65 for(int i = 1; i <= n; i++) { 66 for(int j = 1; j <= m; j++) { 67 if(s[i][j] == '#') continue; 68 for(int k = 0; k < 4; k++) { 69 int nx_x = i + dx[k]; 70 int nx_y = j + dy[k]; 71 if(check(nx_x, nx_y)) { 72 edge[hs[i][j]].push_back(mk(1, hs[nx_x][nx_y])); 73 } 74 } 75 } 76 } 77 78 for(int i = 1; i <= q; i++) { 79 int a, b, c, d; 80 scanf("%d%d%d%d", &a, &b, &c, &d); 81 a++, b++, c++, d++; 82 if(s[a][b] == '#' || s[c][d] == '#') continue; 83 edge[hs[a][b]].push_back(mk(3, hs[c][d])); 84 } 85 86 int ans = Dj(S, T); 87 printf("%d\n", ans); 88 } 89 return 0; 90 } 91 /* 92 */