codevs 1116四色问题 DFS搜索

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

用类似八皇后的思想,就是递归DFS搜索,然后判断当前状态是否合法,是就继续,否就尝试当前点的另一种涂色方案。

代码如下:

#include<iostream>
#include<fstream>
using namespace std;
//四种颜色分别1-4表示
int *res;
int map[10][10];
int count=0;

bool isOK(int i,int n) {
	int now = res[i];
	int j;
	for(j=0;j<i;j++) {
		if(map[i][j]==1) {
		    if(res[i]==res[j]) return false;
		}
	}
    return true;
}

void dfs(int i,int n) {
    if(i==n) {
		count++;
		return;
	}
	int j;
	for(j=1;j<=4;j++) {
	    res[i] = j;
		if(isOK(i,n)) {
            dfs(i+1,n);
		}
	}
}

int main() {
	//cin重定位,提交时去掉
	ifstream cin("F:\\data.in");
    int n;
	cin>>n;
	res = new int[n];
	int i,j;
	for(i=0;i<n;i++)
		for(j=0;j<n;j++) {
		    cin>>map[i][j];
		}
	dfs(0,n);
	cout<<count;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章