• 回溯法---哈密顿回路(5)


    回溯法---哈密顿回路(5)
    在给定图中任取一点,要求经过图中所有点,最后回到起始点,要求同一个点不允许重复经过

    在(2)算法框架基础上:

    import java. util.Vector ;

    public class Hamilton extends CombineProblem {

             int start;

             int[][] graph ;

             public Hamilton(int[][] graph , int start, int n) {
                     this.graph = graph;

                     this.flag = false ;

                     this.n = n;

                     this.x = new Integer[n ];

                     this.start = start - 1;

             }

            @Override
             public Vector<Comparable> makeIterm (int k) {
                    Vector vec = new Vector();
                     if ( k == 0) {
                            vec .add( start);
                     } else
                             for ( int i = 0 ; i < n; i++) {
                                     if ( graph[(Integer ) x[ k - 1]][ i] == 1) {
                                            vec .add( i);
                                     }
                             }
                     return vec;
             }

            @Override
             public boolean complete(int k) {
                     if ( k >= n) {
                             return graph[( Integer) x [k - 1 ]][(Integer) x[0 ]] == 1 ;
                     }
                     return false ;
             }

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

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

    运行结果:

    1 2 5 4 3
    1 3 2 5 4
    1 3 4 5 2
    1 4 5 2 3 




  • 相关阅读:
    C#博客记录二
    C#博客记录一
    label语句
    css选择器
    关于访问对象属性的小问题
    特殊符号unicode编码
    不换行
    正则表达式中的exec()方法
    正则表达式中两种定义方式中的反斜杠
    js删除对象数组
  • 原文地址:https://www.cnblogs.com/ZhangJinkun/p/4531359.html
Copyright © 2020-2023  润新知