码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-05-26 20:43:02      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

回溯法---哈密顿回路(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 




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

标签:

原文地址:http://www.cnblogs.com/ZhangJinkun/p/4531359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!