涂颜色--(深搜和广搜)

https://www.luogu.org/problemnew/show/P1162 

题目描述

由数字00组成的方阵中,有一任意形状闭合圈,闭合圈由数字11构成,围圈时只走上下左右44个方向。现要求把闭合圈内的所有空间都填写成22.例如:6 \times 66×6的方阵(n=6n=6),涂色前和涂色后的方阵如下:

0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1

输入输出格式

输入格式:

 

每组测试数据第一行一个整数n(1 \le n \le 30)n(1≤n≤30)

接下来nn行,由00和11组成的n \times nn×n的方阵。

方阵内只有一个闭合圈,圈内至少有一个00。

//感谢黄小U饮品指出本题数据和数据格式不一样. 已修改(输入格式)

 

输出格式:

 

已经填好数字22的完整方阵。

 

输入输出样例

输入样例#1: 复制

6
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1

输出样例#1: 复制

0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1

说明

1 \le n \le 301≤n≤30

深搜:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
//方阵的最外圈加上一圈零,才能把墙围的外边的零全部找到
int a[32][32],n;
int next[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
void dfs(int p,int q){
	if(p<0||p>n+1||q<0||q>n+1||a[p][q]!=0)  //n+1要理解,加一圈零
	return ;
	a[p][q]=1;
	for(int k=0;k<4;k++){       //搜索上下左右四个点
		dfs(p+next[k][0],q+next[k][1]);
	}
	return ;
}

int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
    	for(int j=1;j<=n;j++){
    		cin>>a[i][j];
    		a[i][j]=(a[i][j]==0?0:2);  //墙标记成2,和后面对墙围外的零的搜索区别
		}
	}
	dfs(0,0);
	for(int i=1;i<=n;i++){
		for(int j=1;j<n;j++){
			if(a[i][j]==0)
			cout<<"2"<<" ";
			else if(a[i][j]==1)
			cout<<"0"<<" ";
			else cout<<"1"<<" ";
		}
		if(a[i][n]==0)
			cout<<"2"<<endl;
			else if(a[i][n]==1)
			cout<<"0"<<endl;
			else  cout<<"1"<<endl;
	}
	return 0;
}

 广搜:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
int a[32][32],n;
struct node{
	int x;
	int y;
};
queue<node> M;
int next[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
void bfs(int p,int q){
	a[p][q]=1;
	node t;
	t.x=p;
	t.y=q;
	M.push(t);
	while(!M.empty()){
		node temp=M.front();
		M.pop();
		for(int k=0;k<4;k++){
			int tx=temp.x+next[k][0];
			int ty=temp.y+next[k][1];
			if(a[tx][ty]!=0||tx<0||tx>n+1||ty<0||ty>n+1)
			continue;
			a[tx][ty]=1;
			node b;
			b.x=tx;
			b.y=ty;
			M.push(b);
		}
		
	}
	return ;
}

int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
    	for(int j=1;j<=n;j++){
    		cin>>a[i][j];
    		a[i][j]=(a[i][j]==0?0:2);
		}
	}
	bfs(0,0);
	for(int i=1;i<=n;i++){
		for(int j=1;j<n;j++){
			if(a[i][j]==0)
			cout<<"2"<<" ";
			else if(a[i][j]==1)
			cout<<"0"<<" ";
			else cout<<"1"<<" ";
		}
		if(a[i][n]==0)
			cout<<"2"<<endl;
			else if(a[i][n]==1)
			cout<<"0"<<endl;
			else  cout<<"1"<<endl;
	}
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值