1116 四色问题
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 黄金 Gold
题解
查看运行结果
题目描述 Description
给定N(小于等于8)个点的地图,以及地图上各点的相邻关系,请输出用4种颜色将地图涂色的所有方案数(要求相邻两点不能涂成相同的颜色)
数据中0代表不相邻,1代表相邻
输入描述 Input Description
第一行一个整数n,代表地图上有n个点
接下来n行,每行n个整数,每个整数是0或者1。第i行第j列的值代表了第i个点和第j个点之间是相邻的还是不相邻,相邻就是1,不相邻就是0.
我们保证a[i][j] = a[j][i] (a[i,j] = a[j,i])
输出描述 Output Description
染色的方案数
样例输入 Sample Input
8
0 0 0 1 0 0 1 0
0 0 0 0 0 1 0 1
0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
1 0 1 0 0 0 0 0
0 1 0 0 0 0 0 0
样例输出 Sample Output
15552
数据范围及提示 Data Size & Hint
n<=8
非常经典一道题,直接暴力搜索,看代码有详细注释。
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<cstdio>
const int INF=0x3f3f3f3f;
typedef long long LL;
const int maxn=100;
using namespace std;
int ans=0;
int N;
int color[maxn];
int a[maxn][maxn];
void dfs(int x) //当前的顶点
{
if(x>N) {ans++;return;}
for(int i=1;i<=4;i++) //枚举四种颜色
{
bool ok=true;
for(int j=1;j<=N;j++) //判断与x相邻的顶点是否有相同颜色的
{
if(a[x][j]&&color[j]==i)
{
ok=false;break;
}
}
if(ok)
{
color[x]=i; //当前顶点x染成i颜色
dfs(x+1);
color[x]=0; //回溯
}
}
}
int main()
{
cin>>N;
for(int i=1;i<=N;i++)
for(int j=1;j<=N;j++)
cin>>a[i][j];
dfs(1); //从第一个顶点开始搜索
cout<<ans<<endl;
return 0;
}