zoukankan      html  css  js  c++  java
  • 回溯法---n-着色问题(3)

    回溯法---n-着色问题(3)
    以三色问题为例:

    对给定无向图着色,相邻点颜色不能相同,限用3种颜色

    在框架基础上的实现:

    import java. util.Vector ;

    public class ThreeColor extends CombineProblem {
        int[][] graph;
        int start ;

        public ThreeColor (int[][] graph, int start) {
             super();
             this.graph = graph;
             this.start = start;
             this.flag = false ;
             this.n = graph. length;
             this.x = new Integer[n];
        }

        @Override
        public Vector <Comparable> makeItem(int k) {
            Vector <Comparable> vec = new Vector<Comparable>();
             for ( int i = 1 ; i <= 3 ; i++) {
                vec .add( i);
             }
             return vec;
        }

        @Override
        public boolean complete (int k) {
             return k >= n;
        }

        @Override
        public void printSolution (int k) {
             for ( int i = 0 ; i < x.length; i ++) {
                System .out. print(x [i] + " ");
             }
            System .out. println();
        }

        @Override
        public boolean isPartial (int k) {
             for ( int i = 0 ; i < k; i++) {
                 if ( graph[k ][i] == 1 && x [k] == x[i ]) {
                     return false ;
                 }
             }
             return true ;
        }

    }

    主函数:

    public class Main {

        public static void main (String[] args) {

             int[][] graph = { { 0, 1 , 1 , 0 }, { 1, 0, 0, 1 }, { 1 , 0 , 0 , 1 },
                     { 0 , 1 , 1 , 0 } };

             Problem p = new ThreeColor(graph , 0 );
            
             p .explore(0);

             if (! p.flag) {
                System .out. println("no solution!" );
             }

        }

    }

    运行结果:

    1 2 2 1
    1 2 2 3
    1 2 3 1
    1 3 2 1
    1 3 3 1
    1 3 3 2
    2 1 1 2
    2 1 1 3
    2 1 3 2
    2 3 1 2
    2 3 3 1
    2 3 3 2
    3 1 1 2
    3 1 1 3
    3 1 2 3
    3 2 1 3
    3 2 2 1
    3 2 2 3 





  • 相关阅读:
    ide 安装eval reset插件 Pycharm 永久破解
    Centos7.9安装RabbitMQ
    Linux环境下安装Centos7.9时没有图形界面的解决办法
    JS,对部分值base64解码
    consul 配置备份
    AutoMapper后遇到的“Missing map”与“Missing type map configuration”问题
    osg绘制圆柱体
    IfcFlowMovingDevice
    opencv absdiff
    IfcFlowMovingDeviceType
  • 原文地址:https://www.cnblogs.com/ZhangJinkun/p/4531361.html
Copyright © 2011-2022 走看看