n皇后问题:
#include<iostream>
using namespace std;
#include<math.h>
bool place(int x[],int k)
{
int i;
for(i=1;i<k;i++){
if((x[i]==x[k])||(abs(x[i]-x[k])==abs(i-k)))
return false;
}
return true;
}
void n_queens(int n,int x[]){
int k=1;
x[1]=0;
while(k>0){
x[k]++;
while((x[k]<=n)&&(!place(x,k)))
x[k]++;
if(x[k]<=n){
if(k==n)break;
else{
k++;
x[k]=0;
}
}
else{
x[k]=0;
k--;
}
}
}
void main(){
int x[10]={0};
int n=8;
n_queens(n,x);
for(int i=1;i<=n;i++)
cout<<x[i]<<" ";
cout<<endl;
}
修改代码,要解决几皇后的问题,就直接把main()函数中的变量n赋值为几,程序运行时不需要再输入。
图的着色问题:
#include<iostream>
#include <fstream>
using namespace std;
#define N 5 //顶点个数
int m; //最大颜色数
int x[N]; //顶点的着色
bool c[N][N]; //布尔值表示的图的邻接矩阵
bool ok(int x[],int k,bool c[][N])
{
int i;
for(i=0;i<k;i++){
if(c[k][i]&&(x[k]==x[i]))
return false;
}
return true;
}
bool m_coloring(int n,int m,int x[],bool c[][N])
{
int i,k;
for(i=0;i<n;i++)
x[i]=0; //解向量初始化为0
k=0;
while(k>=0){
x[k]++; //使当前的颜色数加一
while((x[k]<=m)&&(!ok(x,k,c))) //当前着色是否有效
{
x[k]++; //无效,继续搜索下一种颜色
}
if(x[k]<=m){ //搜索成功
if(k==n-1)break; //是最后的顶点,完成搜索
else k++; //不是,处理下一个结点
}
else{
x[k]=0; //搜索失败,回溯到前一个顶点
k--;
}
}
if(k==n-1)return true;
else return false;
}
void main()
{
ifstream inf("G:\\color.txt");
if(!inf){
cout<<"Cannot open input file\n"<<endl;
exit(1);
}
for(int i=0;i<N;i++)
for(int j=0;j<N;j++){
inf>>c[i][j];
}
inf.close();
if(m_coloring(N,3,x,c))
cout<<"存在有效的着色"<<endl;
else
cout<<"不存在有效的着色"<<endl;
for(i=0;i<N;i++)
cout<<x[i]<<" ";
cout<<endl;
}
file(color.txt):
0 1 1 0 0
1 0 1 1 1
1 1 0 0 1
0 1 0 0 1
0 1 1 1 0
调试运行时注意更改*color.txt*对应的路径
本例解决的图的着色问题对应图如下: