zoukankan      html  css  js  c++  java
  • 回溯法---哈密顿回路(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 




  • 相关阅读:
    web api 特点
    码农
    到程序员短缺的地方生活,不要到过剩的地方凑热闹
    程序员也要寻找贸易的机会,要参加研讨会
    [Codeforces 863D]Yet Another Array Queries Problem
    [Codeforces 863C]1-2-3
    [Codeforces 864F]Cities Excursions
    [Codeforces 864E]Fire
    [Codeforces 864D]Make a Permutation!
    [Codeforces 864C]Bus
  • 原文地址:https://www.cnblogs.com/ZhangJinkun/p/4531359.html
Copyright © 2011-2022 走看看