题目链接
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;
}
}