P1162 填涂颜色

 解法一:

深度优先搜索。搜索第一行和最后一行

搜索第一列和最后一列

标记搜索过的点。

没有搜索到的点就是被包围了

#include <iostream> 
#include <cstring>
#include <cstdio>
using namespace std;

int a[31][31];
int n;
int mark[31][31];

int dx[]={0, -1, 0, 1};
int dy[]={-1, 0, 1, 0};


void dfs(int x, int y)
{
	if(mark[x][y])
		return ;
	mark[x][y] = 1;
	for(int i = 0; i < 4; i++)
	{
		int x0 = x + dx[i];
		int y0 = y + dy[i];
		if( x0 >=1 && x0<=n && y0>=1 && y0<=n && !mark[x0][y0])
		{
			dfs(x0, y0);
		}
	}
	

}
int main()
{
	cin>>n;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			cin>>a[i][j];
			if(a[i][j])
			{
				mark[i][j] = 1;
			}
		}
	}
	//从行与列来进行搜索
	for(int i = 1; i <=n; i++)
	{
		if(!mark[1][i])//搜索一行
			dfs(1, i);
		if(!mark[n][i])//第N行
			dfs(n, i);
		if(!mark[i][1])//第一列
			dfs(i, 1);
		if(!mark[i][n])//第n列
			dfs(i, n);
	}
    for(int i = 1; i <= n ; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			if(!mark[i][j])
				cout<<2<<" ";
			else
				cout<<a[i][j]<<" ";
		}
		cout<<endl;
	}
    //system("pause");
}

 

解法二:广度优先搜索

找到第一个1,其右下角就是0了,就是包围的0

从这个0开始广度优先搜索染色 

#include <iostream> 
#include <cstring>
#include <cstdio>
#include<queue>

using namespace std;
struct node
{
	int x, y;
};
queue<node>Q;
int a[31][31];
int n;
int mark[31][31];

int dx[]={0, -1, 0, 1};
int dy[]={-1, 0, 1, 0};

void bfs(int x, int y)
{
	mark[x][y] = 2;
	
	node tnode;
	node tempnode;
	tnode.x = x;
	tnode.y = y;
	Q.push(tnode);
	while(!Q.empty())
	{
		tempnode = Q.front();
		Q.pop();
		for(int i = 0; i < 4; i++)
		{
			int x0 = tempnode.x + dx[i];
			int y0 = tempnode.y +dy[i];
			if(x0>=1 && x0<=n && y0>=1&&y0<=n && !mark[x0][y0] && a[x0][y0] != 1)
			{
				mark[x0][y0] = 2;
				tnode.x = x0;
				tnode.y = y0;
				Q.push(tnode);
			}
		}

	}

}
int main()
{
	cin>>n;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			cin>>a[i][j];
			
		}
	}

	int x,y;
	int tag = false;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			if(a[i][j])
			{
				x = i+1;
				y = j+1;
				tag = true;
				break;
			}
			
		}
		if(tag)
			break;
	}
	//cout<<x<<" "<<y;
	//system("pause");
	bfs(x, y);
	//cout<<endl;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			if(mark[i][j] == 2)
				cout<<2<<" ";
			else
				cout<<a[i][j]<<" ";

			
		}
		cout<<endl;
	}

   // system("pause");
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值