Connect(CF 1130C)——BFS

题目链接:http://codeforces.com/problemset/problem/1130/C
题目大意:地图上有土地和水,爱丽丝要从起点到终点,但是她只能走土地,所以我们要建造最多一只桥让她到达终点。建桥的消耗是两点之间的距离的平方,问消耗最少是多少。

题解:就是两个队列,一个放起点能到的位置,一个放终点能到的位置,然后就遍历完所有的可行点的建桥消耗,取最小值。

起始可以将起点能走的区域的点的位置存起来,终点能走的点也存起来,然后最后算建桥的消耗,这种方法更优,前面那种就比较麻烦。

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <math.h>
#include <string.h>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <map>

#define INF 0x3f3f3f3f
const int MAX=0x3f3f3f3f;

using namespace std;
typedef long long ll;

struct node{
    int x,y;
};
const int a[4][2]={
        0,1,
        1,0,
        0,-1,
        -1,0
};
char mp[55][55];
char exmp[55][55];
int n,r1,c1,r2,c2;
int ans;

int bfs(int ex,int ey)
{
    node tt;
    tt.x=ex;
    tt.y=ey;
    queue<node>end_q;
    end_q.push(tt);
    mp[end_q.front().x][end_q.front().y]='1';
    ans=(r1-r2)*(r1-r2)+(c1-c2)*(c1-c2);
    while(!end_q.empty())
    {
        int ttmp=(r1-end_q.front().x)*(r1-end_q.front().x)+(c1-end_q.front().y)*(c1-end_q.front().y);
        if(ttmp<ans)
            ans=ttmp;
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                exmp[i][j]=mp[i][j];
            }
        }
        node temp;
        temp.x=r1;
        temp.y=c1;
        queue<node>begin_q;
        begin_q.push(temp);
        exmp[begin_q.front().x][begin_q.front().y]='1';
        while(!begin_q.empty())
        {
            for(int i=0;i<4;i++)
            {
                temp.x=begin_q.front().x+a[i][0];
                temp.y=begin_q.front().y+a[i][1];
                if(temp.x==r2&&temp.y==c2)
                    return 0;
                if(exmp[temp.x][temp.y]=='1'||temp.x>n||temp.y>n||temp.x<=0||temp.y<=0)
                    continue;
                begin_q.push(temp);
                exmp[temp.x][temp.y]='1';
                int tans=(temp.x-end_q.front().x)*(temp.x-end_q.front().x)+(temp.y-end_q.front().y)*(temp.y-end_q.front().y);
                if(ans>tans)
                    ans=tans;
            }
            begin_q.pop();
        }
        for(int i=0;i<4;i++)
        {
            node tmp;
            tmp.x=end_q.front().x+a[i][0];
            tmp.y=end_q.front().y+a[i][1];
            if(tmp.x==r1&&tmp.y==c1)
                return 0;
            if(mp[tmp.x][tmp.y]=='1'||tmp.x>n||tmp.y>n||tmp.x<=0||tmp.y<=0)
                continue;
            end_q.push(tmp);
            mp[tmp.x][tmp.y]='1';
        }
        end_q.pop();
    }
    return ans;
}

int main()
{
    while(~scanf("%d",&n))
    {
        scanf("%d%d%d%d",&r1,&c1,&r2,&c2);
        getchar();
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
                scanf("%c",&mp[i][j]);
            getchar();
        }
        int final=bfs(r2,c2);
        printf("%d\n",final);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44049850/article/details/88057731
今日推荐