J - Robots at Warehouse ( dfs + 思维 )

J - Robots at Warehouse ( dfs + 思维 )

题目链接https://vjudge.net/problem/Gym-100971J

题意:在一个N*M的图中,’.’ 代表可以走的路,’1’代表第一个机器人,’2’代表第二个机器人,’#’代表墙,问你两个机器人能不能交换地方。仔细读题,有一句话说的是所有路都是连通的(很重要)。

思路: 只需要判断所有路上有没有一个度数大于三的点。度数大于三的点意味着在这个地方两个机器人可以错一下位,也就能换地方了。还需要注意一个特例,当没有度数大于三的点时,所有路径可能成一个环,这样也是可以的。

Input

5 3
###
#1#
#.#
#2#
###

Output

NO

Input

3 5
#...#
#1.2#
#####

Output

YES

代码:

#include <bits/stdc++.h>

using namespace std;

int n,m,cnt,isp;
int nxt[4][2] = {0,1,0,-1,1,0,-1,0};
char a[2000005];
int via[2000005];

void dfs( int x, int y )
{
    if ( isp==1 || cnt>=2 ) return ; // 注意及时return , 不然T20
    if ( a[x*m+y]=='2' ) {
        cnt ++;
        // 这里不要return,到2了可能还要往其他地方走
        // return ;
    }
    via[x*m+y] = 1;
    int d = 0;
    for ( int i=0; i<4; i++ ) {
        int xx = x + nxt[i][0];
        int yy = y + nxt[i][1];
        if ( xx<0||yy<0||xx>=n||yy>=m ) continue;
        if ( a[xx*m+yy]!='#' ) d++;
    }
    if ( d>=3 ) isp = 1;
    for ( int i=0; i<4; i++ ) {
        int xx = x + nxt[i][0];
        int yy = y + nxt[i][1];
        if ( xx<0||yy<0||xx>=n||yy>=m ) continue;
        if ( via[xx*m+yy]==1 ) continue;
        if ( a[xx*m+yy]!='#' && via[xx*m+yy]==0 ) dfs(xx,yy);
    }
    via[x*m+y] = 0;
}

int main()
{
    cin>>n>>m;
    int x,y;
    for ( int i=0; i<n; i++ ) {
        for ( int j=0; j<m; j++ ) {
            char str;cin>>str;
            a[i*m+j] = str;
            if ( str=='1' ) x=i,y=j;
        }
    }
    dfs(x,y);
    if ( isp==1 || cnt>=2 ) cout << "YES" << endl;
    else cout << "NO" << endl;

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值