[codeforces 1365D] Solve The Maze 遍历矩阵的深搜dfs+隔断的设置

Codeforces Round #648 (Div. 2)  参与排名人数13231

[codeforces 1365D]     Solve The Maze   遍历矩阵的深搜+隔断的设置

总目录详见https://blog.csdn.net/mrcrack/article/details/103564004

在线测评地址https://codeforces.com/contest/1365/problem/D

Problem Lang Verdict Time Memory
D - Solve The Maze GNU C++17 Accepted 31 ms 100 KB

熟悉深搜的读者,以下代码还是容易看懂的,采用的是记忆化搜索,唯一的技巧就是隔断的设置

if(mp[nr][nc]=='B'){vis[r][c]=-1;return;}

请读者慢慢揣摩。

AC代码如下

#include 
int n,m,vis[55][55],k[][2]={{-1,0},{1,0},{0,-1},{0,1}};//UP,DOWN,LEFT,RIGHT
char mp[55][55];
void dfs(int r,int c){
	int nr,nc,i;
	if(vis[r][c]!=0)return;
	if(mp[r][c]=='#'||mp[r][c]=='B'){vis[r][c]=-1;return;}//遇到墙,遇到坏蛋
	for(i=0;i<4;i++){
		nr=r+k[i][0],nc=c+k[i][1];
		if(1<=nr&&nr<=n&&1<=nc&&nc<=m)
			if(mp[nr][nc]=='B'){vis[r][c]=-1;return;}//找坏蛋,设置墙,A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.虽然有此句的限制,但是还是可以设置vis[r][c]=-1
	}
	vis[r][c]=1;//mp[r][c]=='G','.'
	for(i=0;i<4;i++){
		nr=r+k[i][0],nc=c+k[i][1];
		if(1<=nr&&nr<=n&&1<=nc&&nc<=m)
			if(!vis[nr][nc])dfs(nr,nc);//mp[nr][nc]=='G','.','#'
	}
}
void solve(){
	int i,j,flag=0;
	scanf("%d%d",&n,&m);
	for(i=1;i<=n;i++)
		for(j=1;j<=m;j++)
			vis[i][j]=0;
	for(i=1;i<=n;i++)scanf("%s",mp[i]+1);
	dfs(n,m);
	for(i=1;i<=n;i++){
		for(j=1;j<=m;j++)
			if(mp[i][j]=='G'&&vis[i][j]!=1){flag=1;break;}//vis[i][j]==1,'G'没有被访问到;vis[i][j]==-1,或者为了挡住'B',不得不挡住'G'
		if(flag)break;
	}
	if(flag)printf("No\n");
	else printf("Yes\n");
}
int main(){
	int t;
	scanf("%d",&t);
	while(t--)solve();
	return 0;
}

 

你可能感兴趣的:(codeforces)