N皇后问题
#include<iostream>
using namespace std;
#define n 4
int count;
int x[n+1];
int place(int q) {
int i;
for(i = 1; i < q; i++) {
if(abs(q-i)==abs(x[q]-x[i])||x[q]==x[i]) {
return 0;
}
}
return 1;
}
void BackTrack(int q) {
if(q > n) {
for(int i = 1; i <= n; i++) {
cout<<x[i]<<" ";
}
cout<<endl;
count++;
}
for (int j=1; j<=n; j++) {
x[q] = j;
if(place(q) == 1) {
BackTrack(q+1);
}
}
}
int main() {
BackTrack(1);
cout<<count<<endl;
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
图涂色问题
#include<iostream>
using namespace std;
int c[100][100];
int color[100];
int count,m,n;
int Check(int k) {
for(int i = 1; i <= k; i++) {
if(c[k][i]==1&&color[i]==color[k])
return 0;
}
return 1;
}
void graphColor(int step) {
if(step==n+1) {
for(int i=1; i<=n; i++)
cout<<color[i];
count++;
cout<<endl;
return ;
} else {
for(int i=1; i<=m; i++) {
color[step]=i;
if(Check(step)==1) {
graphColor(step+1);
}
color[step]=0;
}
}
}
int main(void) {
cin>>n>>m;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++) {
cin>>c[i][j];
}
graphColor(1);
cout<<count;
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43