码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3170(Knights of Ni)(BFS)

时间:2016-08-01 19:44:18      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

题目地址: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;
}


POJ 3170(Knights of Ni)(BFS)

标签:

原文地址:http://blog.csdn.net/wang2147483647/article/details/52088410

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!