验证四色原理
描述
验证任何一个平面存在一种着色方案,使得相连的区域颜色不同,且颜色种类不大于4;
输入
第一行输入n。第2n+1行:每行表示1n个省,相邻的省用1表示(本身不与本身相邻)。
输出
输出每种可以填色的方式
输入样例 1
7
0 1 0 0 0 0 1
1 0 1 1 1 1 1
0 1 0 1 0 0 0
0 1 1 0 1 0 0
0 1 0 1 0 1 0
0 1 0 0 1 0 1
1 1 0 0 0 1 0
输出样例 1
1 2 1 3 1 3 4 (这是其中的一种,并按字典顺序输出)
#include <bits/stdc++.h>
using namespace std;
int has[25];
int c[25][25];
int n ;
void input ()
{
cin >> n ;
for(int i = 1 ; i<= n ; i++)
for(int j = 1 ; j<= n ; j++)
cin >> c[i][j];
}
bool pan(int d , int co)
{
for(int a = 1 ; a <= d-1 ; a++ ) // 查到 n-1 (不能搜到自己本身)
if(c[d][a] == 1 &&has[a] == co )
return 0; // 空格 划开层次
return 1;
}
int dfs(int dep )
{
if(dep>n) //逻辑表达式要对 (dep > n ) || (dep == n+1)
{
for(int i = 1 ; i <= n ; i++)
cout << has[i] << " ";
cout<<endl;
exit(0);
}
else
{
for(int co = 1 ; co <= 4 ; co++)
{
has[dep] = co ; //要先赋值才能判断
if(pan(dep,co))
dfs(dep+1);
}
}
}
int main()
{
input ();
dfs(1);
return 0 ;
}