題目描述 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<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1000+1;
bool a[maxn][maxn];
int c[maxn];
bool pd=0;
int n,ans;
int dfs(int k)
{
if(k==n+1) ans++;
else for(int i=1;i<=4;i++)
{
for(int j=1;j<=n;j++)
if(c[j]==i&&a[k][j])
{
pd=1;//k號點不能再塗第i種顏色
//break;
}
if(pd==0)
{
c[k]=i;
dfs(k+1);
}
pd=0;
}
c[k]=0;
return ans;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%d",&a[i][j]);
cout<<dfs(1)<<'\n';
return 0;
}