圖的m着色問題

 

 

完整程序:

#include<bits/stdc++.h>
using namespace std;
//圖的m着色問題回溯算法
//(1) 圖的m着色問題回溯算法的數據結構
#define NUM 100
int n;				//圖的頂點數量
int m;			//可用顏色數量
int a[NUM][NUM];	//圖的鄰接矩陣
int x[NUM];		//當前的解向量
int sum ;			//已經找到的可m着色的方案數量
//(3) 檢查相鄰結點的着色是否一樣的約束函數
//形參t是回溯的深度
bool Same(int t)
{
int i;
for(i=1;i<=n;i++ )
if((a[t][i]==1)&&(x[i]==x[t]))
return false;
return true;
}
//(2) 圖的m着色問題回溯算法的實現
//形參t是回溯的深度,從1開始
void BackTrack(int t)
{
int i;
//到達葉子結點,獲得一個着色方案
if(t>n)
{
sum++;
for(i=1;i<=n;i++)
printf("%d ",x[i]);
printf("\n");
}
else
//搜索當前擴展結點的m個孩子
for(i=1;i<=m;i++)
{
x[t]=i;
if(Same(t))BackTrack(t+1);
x[t]=0;
}
}
int main(){
  cout<<"請輸入頂點的個數和顏色數"<<endl;
    cin>>n>>m;
    int a1,a2;
   //memset(a,0,sizeof(a));
    while(cin>>a1>>a2){
         if(a1||a2){
            a[a1][a2]=1;
               a[a2][a1]=1;
         }
         else break;
    }
    cout<<"所有的着色方案爲"<<endl;
     BackTrack(1);
    cout<<"着色方案總數爲"<<endl;
    cout<<"Total="<<sum;
return 0;
}

 

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