P1162 填涂颜色 BFS 题解

逆向思维,把闭合圈外的0全部消灭,剩下闭合圈里的0
实现方法:在原有的矩阵基础上四周再加一层,保证所有闭合圈外的的0都能扫描到

我的代码:

#include<bits/stdc++.h>
using namespace std;
int n;
int a[50][50], dx[4]={0, -1, 0, 1}, dy[4]={-1, 0, 1, 0};

void dfs(int x, int y){
	if(x<0 || x>n+1 || y<0 || y>n+1 || a[x][y])
		return;
	
	a[x][y] = 3;
	
	for(int i=0; i<4; i++)
		dfs(x+dx[i], y+dy[i]);
}

int main(){
	cin>>n;
	
	for(int i=1; i<=n; i++){
		for(int j=1; j<=n; j++){
			cin>>a[i][j];
		}
	}
	
	dfs(0, 0);
	
	for(int i=1; i<=n; i++){
		for(int j=1; j<=n ;j++){
			if(a[i][j]==3){
				cout<<"0 ";
			}else if(a[i][j]==1){
				cout<<"1 ";
			}else{
				cout<<"2 ";
			}
		}
		cout<<endl;
	}
	
} 
发布了46 篇原创文章 · 获赞 1 · 访问量 2420

猜你喜欢

转载自blog.csdn.net/weixin_43708069/article/details/104004942