c++实现回溯算法解决图的M着色问题
开发环境:eclipse+MINGW
编程语言:C++
主程序main.cpp
算法程序mColor.h
输入文件 input.txt
文本文件中每一行表示第I个国家相邻的国家编号
下载地址:http://download.youkuaiyun.com/detail/wizholy/4696388
/*
* Main.cpp
*
* Created on: 2012-10-20
* Author: Wizholy
*/
#include<iostream>
#include"mColor.h"
#include<iomanip>
#include<string>
//#include"mColor.h"
using namespace std;
bool fileInit(int &n,int &max)//
{
return false;
}
int main()
{
cout<<"图的M着色问题解决方法:"<<endl<<"输入数据为:"<<endl;
Color col(7);
if(!col.exploreMap(0,1)){cout<<"着色失败!"<<endl;return 0;}
for(int i=0;i<col.number;i++)
{
cout<<"第"<<setw(3)<<"个国家的颜色是:";
switch(col.x[i])
{
case 0: cout<<"NONE";break;
case 1: cout<<"RED";break;
case 2: cout<<"YELLOW";break;
case 3: cout<<"GREEN";break;
case 4: cout<<"BLUE";break;
}
cout<<endl;
}
}
/*
* mColor.h
*
* Created on: 2012-10-20
* Author: Wizholy
*/
#ifndef MCOLOR_H_
#define MCOLOR_H_
#include<fstream>
#include<string>
#include<sstream>
#include<iomanip>
using namespace std;
class Color
{
public:
int** map;
int number;
int *mapColors;
int *x;
Color(int num);
void createMap(int n);
void print(int n);
bool exploreMap(int county,int color);
bool okToMap(int county,int color);
//获取第N个国家相邻国家的个数
int length(int n)
{
int i=0;
for(;i<1024;i++)
{
if(map[n][i]==-1) break;
else i++;
}
return i;
}
};
bool Color::exploreMap(int county,int color)
{
if(county>=number) return true; //表示搜索完毕,
if(okToMap(county,color))
{
x[county]=color;
for(int j=1;j<=4;j++)
{
if(exploreMap(county+1,j))
return true;
}
}
return false;
}
bool Color::okToMap(int county,int color)
{
for(int i=0;i<length(county);i++){
int adjCounty=map[county][i];
if(x[adjCounty]==color){
return false;
}
}
return true;
//x[county]=RED;
}
//从文件中建立地图的数组
Color::Color(int num)
{
createMap(num);
number=num;
x=new int[number];
for(int i=0;i<number;i++)
{
x[i]=0;
}
}
void Color::createMap(int n)
{
ifstream in("input.txt");
char buff[1024];
map=new int*[n];
for(int k=0;k<n;k++)
{
map[k]=new int[n];
for(int p=0;p<n;p++){map[k][p]=-1;}
}
int i=0;
while(!in.eof())
{
in.getline(buff,100);
string str(buff);
stringstream ss(str);
int temp;
int j=0;
while(ss>>temp)
{
map[i][j]=temp;
j++;
cout<<setw(5)<<temp;
}
i++;
cout<<endl;
}
in.close();
print(i);
}
//打印结果矩阵
void Color::print(int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(map[i][j]!=-1)
cout<<setw(5)<<map[i][j];
}
cout<<endl;
}
}
#endif /* MCOLOR_H_ */
1 4 2 5
0 4 6 5
0 4 3 6 5
2 4 6
0 1 6 3 2
2 6 1 0
2 3 4 1 5
程序运行结果:
图的M着色问题解决方法:
输入数据为:
1 4 2 5
0 4 6 5
0 4 3 6 5
2 4 6
0 1 6 3 2
2 6 1 0
2 3 4 1 5
1 4 2 5
0 4 6 5
0 4 3 6 5
2 4 6
0 1 6 3 2
2 6 1 0
2 3 4 1 5
第个国家的颜色是:RED
第个国家的颜色是:YELLOW
第个国家的颜色是:YELLOW
第个国家的颜色是:RED
第个国家的颜色是:GREEN
第个国家的颜色是:GREEN
第个国家的颜色是:BLUE