回溯法 | 图的m着色问题

学习链接:算法 图的M着色问题


 

虽然今早9点才醒来,10点才来教室,但是coding得很高效。吃个早餐,拉个粑粑的时间,就把算法书上的【图的m着色】问题看明白了,大脑里也形成了解决问题的框架。

其实这个问题很简单,也是使用回溯法的解题方案。半局LOL的功夫,就coding完成。经过简单调试后得到了与书上一样的输出。

Java代码:

 1 import java.util.*;
 2 
 3 
 4 public class Main {
 5 
 6     public static void main(String[] args) {
 7         //图的m色 demo
 8         int adjMatrix[][]={
 9                 {0,1,1,1,0},
10                 {1,0,1,1,1},
11                 {1,1,0,1,0},
12                 {1,1,1,0,1},
13                 {0,1,0,1,0}
14         };
15         M_Color_In_Graph problem=new M_Color_In_Graph(adjMatrix,4);
16         System.out.print(problem);
17         int a;
18         a=0;
19         
20     }
21 }
22 
23 class M_Color_In_Graph{
24     int vexnum=0;//顶点数目
25     int[][] adjMatrix;//邻接矩阵
26     int m=0;
27     List<int[]> solved =new ArrayList<int[]>();//解向量组
28     public String toString(){
29         int i,j;
30         String str=new String("");
31         for(i=0;i<solved.size();i++){
32             int [] out=solved.get(i);
33             for(j=0;j<out.length;j++){
34                 str+=out[j];
35                 str+=" ";
36             }
37             str+="\n";
38         }
39         str+="total="+solved.size();
40         return str;
41     }
42     M_Color_In_Graph(int[][] adj,int m){
43         adjMatrix=adj;
44         vexnum=adj.length;
45         this.m=m;
46         BackTrace(0,null);
47     }
48     void BackTrace(int t,int[] x){//对顶点t进行着色,父结点的解向量为x
49         if(t<vexnum){
50             int i,j;
51             //对x的下标t赋m个值
52             for(i=0;i<m;i++){
53                 int[] cx=new int[vexnum];    //新建子结点
54                 for(j=0;j<t;j++) cx[j]=x[j];//拷贝父结点
55                 cx[t]=i;
56                 if(contraint(cx,t)) BackTrace(t+1,cx);
57             }
58         }else{//着色完毕
59             solved.add(x);
60         }
61     }
62     boolean contraint(int[] x,int len){//约束函数
63         //对图进行遍历。如果【所有结点】满足【图中两个结点连通,并且颜色不等】,true。
64         int i,j;
65         for(i=0;i<len;i++){
66             for(j=i+1;j<=len;j++){
67                 if( adjMatrix[i][j]>0 //如果图是连通的
68                     && x[i]==x[j] ){//但是这两个顶点颜色相同
69                     return false;
70                 }
71             }
72         }
73         return true;
74     }
75 }

 

posted @ 2017-10-14 11:26  TQCAI  阅读(1257)  评论(0编辑  收藏  举报