题目地址:http://poj.org/problem?id=3170
思路:两次BFS,先从起点到shrubbery点求最短路,再从终点到shrubbery求最短路,枚举shrubbery点,取最小值。
#include<cstdio> #include<queue> #include<cstring> #include<iostream> #include<algorithm> #define debu using namespace std; const int dx[]= {-1,1,0,0}; const int dy[]= {0,0,-1,1}; const int INF=0x3f3f3f3f; const int maxn=1000+50; struct Node { int x,y; Node(int x=0,int y=0):x(x),y(y) {} }; queue<Node> q; vector<Node> shr; int n,m,stx,sty,edx,edy; int dist[2][maxn][maxn]; int g[maxn][maxn],v[maxn][maxn]; void solve(int id,int x,int y) { memset(v,0,sizeof(v)); while(!q.empty()) q.pop(); memset(dist[id],INF,sizeof(dist[id])); v[x][y]=1,q.push(Node(x,y)),dist[id][x][y]=0; while(!q.empty()) { Node now=q.front(); q.pop(); for(int i=0; i<4; i++) { int x=now.x+dx[i]; int y=now.y+dy[i]; if(x>=1&&x<=n&&y>=1&&y<=m&&(g[x][y]!=1)&&(!v[x][y])) { dist[id][x][y]=dist[id][now.x][now.y]+1; v[x][y]=1,q.push(Node(x,y)); } } } } int main() { #ifdef debug freopen("in.txt","r",stdin); #endif // debug scanf("%d%d",&m,&n); for(int i=1; i<=n; i++) for(int j=1; j<=m; j++) { scanf("%d",&g[i][j]); if(g[i][j]==4) shr.push_back(Node(i,j)); if(g[i][j]==2) stx=i,sty=j; if(g[i][j]==3) edx=i,edy=j; } solve(0,stx,sty); solve(1,edx,edy); int ans=INF; for(int i=0; i<shr.size(); i++) { int x=shr[i].x; int y=shr[i].y; ans=min(ans,dist[0][x][y]+dist[1][x][y]); } printf("%d\n",ans); return 0; }
时间: 2024-11-06 06:59:07