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;
}