atcode 339 D - Synchronized Players

题目链接

bfs : 四维 时间复杂度O(n^4); n<=60;

#include<bits/stdc++.h>
using namespace std;
const int N = 65;
int n;
char s[N][N];
int st[N][N][N][N];
int dist[N][N][N][N];
struct p{
    int a,b,c,d;
};
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int res=1e9;
void bfs(int x1,int y1,int x2,int y2)
{
    queue<p>qu;
    qu.push({x1,y1,x2,y2});
    st[x1][y1][x2][y2]=1;
    dist[x1][y1][x2][y2]=0;
    while(qu.size())
    {
        auto t=qu.front(); qu.pop();
        for(int i=0;i<4;i++)
        {
            int a=dx[i]+t.a,b=dy[i]+t.b,c=dx[i]+t.c,d=dy[i]+t.d;
            if(s[a][b]=='#'||a>n||a<1||b>n||b<1) a=t.a,b=t.b;
            if(s[c][d]=='#'||c>n||c<1||d>n||d<1) c=t.c,d=t.d;
            if(st[a][b][c][d]) continue;
            st[a][b][c][d]=1;
            dist[a][b][c][d]=min(dist[a][b][c][d],dist[t.a][t.b][t.c][t.d]+1);
            qu.push({a,b,c,d});
            if(a==c&&b==d) res=min(res,dist[a][b][c][d]);
            
        }
    }
}
int main()
{
    memset(dist,0x3f,sizeof dist);
    cin>>n; int x[2],y[2],k=0;
    for(int i=1;i<=n;i++) for(int j=1;j<=n;j++)
    {
        cin>>s[i][j];
        if(s[i][j]=='P')    x[k]=i,y[k++]=j;
        
    }

    bfs(x[0],y[0],x[1],y[1]);
    if(res==1e9) cout<<-1;
    else
    cout<<res;
}

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值