在给定图中任取一点,要求经过图中所有点,最后回到起始点,要求同一个点不允许重复经过
在(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