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;
}

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