https://codeforces.com/contest/1130/problem/C

题解:两遍BFS+暴力

/*
*@Author:   STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=100+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m,k,sx,sy,ex,ey;
int ans,cnt,flag,temp;
bool a[N][N];
int b[N][N];
bool vis1[N][N];
bool vis2[N][N];
int dist[][2]={1,0,0,1,-1,0,0,-1};
char str[N][N];
struct node{
    int x,y;
}s,tmp,f;
int main()
{
#ifdef DEBUG
	freopen("input.in", "r", stdin);
	//freopen("output.out", "w", stdout);
#endif
    scanf("%d",&n);
    scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
    //scanf("%d",&t);
    //while(t--){}
    for(int i=1;i<=n;i++)
        scanf("%s",str[i]+1);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(str[i][j]=='1')
                a[i][j]=1;
            else
                a[i][j]=0;
        }
    }
    queue<node>q;
    s.x=sx;
    s.y=sy;
    q.push(s);
    vis1[sx][sy]=1;
    while(!q.empty()){
        f=q.front();
        q.pop();

        for(int i=0;i<4;i++){
            tmp.x=f.x+dist[i][0];
            tmp.y=f.y+dist[i][1];
            if(tmp.x<1||tmp.x>n||tmp.y<1||tmp.y>n)
                continue;
            if(vis1[tmp.x][tmp.y]||a[tmp.x][tmp.y])
                continue;
            vis1[tmp.x][tmp.y]=1;
            q.push(tmp);
        }
    }
    while(!q.empty())
        q.pop();
    s.x=ex;
    s.y=ey;
    q.push(s);
    vis2[ex][ey]=1;
    ans=(ex-sx)*(ex-sx)+(ey-sy)*(ey-sy);
    for(int j=1;j<=n;j++){
        for(int k=1;k<=n;k++){
            if(vis1[j][k]){
                ans=min(ans,(j-ex)*(j-ex)+(k-ey)*(k-ey));
            }
        }
    }
    while(!q.empty()){
        f=q.front();//cout<<f.x<<' '<<f.y<<endl;
        q.pop();
        for(int i=0;i<4;i++){
            tmp.x=f.x+dist[i][0];
            tmp.y=f.y+dist[i][1];
            if(tmp.x<1||tmp.x>n||tmp.y<1||tmp.y>n)
                continue;
            if(vis2[tmp.x][tmp.y]||a[tmp.x][tmp.y])
                continue;
            vis2[tmp.x][tmp.y]=1;
            for(int j=1;j<=n;j++){
                for(int k=1;k<=n;k++){
                    if(vis1[j][k]){
                        ans=min(ans,(j-tmp.x)*(j-tmp.x)+(k-tmp.y)*(k-tmp.y));
                    }
                }
            }
            if(vis1[tmp.x][tmp.y])
                break;
            q.push(tmp);
        }
    }
    cout << ans << endl;
    //cout << "Hello world!" << endl;
    return 0;
}