CF445A - DZY Loves Chessboard

题目链接

https://codeforces.com/contest/445/problem/A

题目描述

题目描述

解题思路

二维表格上的图遍历和图着色,因为只需要对方格填两种颜色,因此在搜索着色的过程中,不需要判断相邻的颜色是否相同,只需和上一次涂的颜色不同即可。

参考代码

下列代码中用数2和3分别代表白色和黑色。

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

const int MAXN=102;
bool board[MAXN][MAXN];
bool visited[MAXN][MAXN];
int ans[MAXN][MAXN];
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};

void dfs(int x ,int y ,int last_color );
bool check(int x,int y );
void printArray(int n);

int main(){
	int n,m;
	string str;	
	cin>>n>>m;
	
	for(int i=1; i <= n; ++i ){
		cin>>str;
		for(int j = 0; j < str.length(); ++j ){
			if( str[j] == '.' )
			board[i][j+1] = true;
		}
	}
	
	//test board's values
	//printArray(n);
	
	for( int i = 1; i <= n; ++i ) {
		for( int j = 1; j <= m; ++j ) {
			if( check( i, j ) )
				dfs( i, j, 2 );
		}
	}
	
	for( int i = 1; i <= n; ++i ) {
		for( int j = 1; j <= m; ++j ) {
			switch( ans[i][j] ){
				case 0: cout<<"-"; break;
				case 2: cout<<"W"; break;
				case 3: cout<<"B"; break;
			}
		}
		cout<<endl;
	}	
	
	return 0;
}

void dfs(int x ,int y ,int last_color ){
	
	visited[x][y] = true;
	ans[x][y]= ( last_color^1 );
	
	for(int i = 0; i < 4; ++i){
		int tx = x + dx[i];
		int ty = y + dy[i];	
		if( check(tx,ty) )
			dfs( tx,ty,ans[x][y] );
	}
				
}

bool check(int x,int y){
	if( board[x][y] == false || visited[x][y]   ) 	
		return false;
		
	return true;
}

void printArray(int n){
	for(int i = 1; i <= n; ++i ){
		for(int j = 1; j <= n; ++j)
			cout<< board[i][j] << " ";
		cout<<endl;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值