一开始是MLE,后来想到了用vector,化二维为一维,做了这一步优化后,这就是很基础的一个广搜了
#include<iostream> #include<cstdio> #include<cstring> #include<queue> #include<cmath> #include<vector> using namespace std; #define maxn 510 char maps[maxn][maxn]; vector<int>v[maxn*maxn]; int vis[maxn][maxn],go[4][2] = {1,0,0,1,0,-1,-1,0},n,m; struct Pos { int x,y,s; }node; bool ok(Pos a) { return (a.x>=0 && a.x<n && a.y>=0 && a.y<m && maps[a.x][a.y] != '#' && !vis[a.x][a.y]); } int bfs(Pos a,Pos b) { queue<Pos> que; memset(vis,0,sizeof(vis)); while(!que.empty()) que.pop(); vis[a.x][a.y] = 1; que.push(a); while(!que.empty()) { Pos now = que.front(); que.pop(); if(now.x == b.x && now.y == b.y) return now.s; Pos nxt; for(int i = 0;i < 4;i++) { nxt.x = now.x + go[i][0]; nxt.y = now.y + go[i][1]; if(ok(nxt)) { vis[nxt.x][nxt.y] = 1; nxt.s = now.s + 1; que.push(nxt); } } int s = now.x*m + now.y; for(int i = 0;i < v[s].size();i++) { nxt.x = v[s][i] / m; nxt.y = v[s][i] % m; if(ok(nxt)) { vis[nxt.x][nxt.y] = 1; nxt.s = now.s + 1; que.push(nxt); } } } } int main() { while(~scanf("%d%d",&n,&m)) { Pos node1,node2; for(int i = 0;i < n;i++) scanf("%s",maps[i]); int k,x,y,st,en; for(int i = 0;i < n;i++) { for(int j = 0;j < m;j++) { if(maps[i][j] == 's') node1.x = i,node1.y = j,node1.s = 0; else if(maps[i][j] == 't') node2.x = i,node2.y = j,node2.s = 0; st = i*m + j; v[st].clear(); scanf("%d",&k); while(k--) { scanf("%d%d",&x,&y); x--,y--; en = x*m + y; v[st].push_back(en); } } } printf("%d ",bfs(node1,node2)); } }