Hamilton

package com.test;

import java.util.Vector;

public class Hamilton {

	protected int start;
	protected int a[][];
	protected int len;
	protected int x[]; // 记录回路
	protected boolean flag;

	public Hamilton(int[][] a, int n, int start) {
		this.a = a;
		this.len = n;
		this.flag = false;
		this.x = new int[n];
		this.start = start - 1;
	}

	public boolean isComplete(int k) {
		return a[x[k - 1]][x[0]] == 1;
	}

	public Vector<Integer> makeIterms(int k) {
		Vector<Integer> iterms = new Vector<Integer>();
		if (k == 0) {
			iterms.add(start);
		} else {
			for (int i = 0; i < len; i++)
				if (a[x[k - 1]][i] == 1) // 相当重要
					iterms.add(i);
		}
		return iterms; // 第k-1层结点的所有临界点
	}

	public void printSolution(int k) {
		System.out.print(x[0] + 1);
		for (int i = 1; i < len; i++)
			System.out.print("->" + (x[i] + 1));
		System.out.println("->" + (x[0] + 1));
	}

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

public class General {
	// 回溯算法的引导框架
	public static void backtrack(Hamilton p) {
		explore(p, 0);
		if (!p.flag)
			System.out.println("no sulution!");
	}

	// 回溯算法的探索框架
	private static void explore(Hamilton p, int k) {
		if (k >= p.len) {
			if (p.isComplete(k)) {
				p.flag = true;
				p.printSolution(k);
			}
			return;
		}
		Vector<Integer> iterms = p.makeIterms(k);
		for (int i = 0; i < iterms.size(); i++) {
			p.x[k] = iterms.get(i);
			if (p.isPartial(k))
				explore(p, k + 1);
		}
	}

	public static void main(String args[]) {
		int c[][] = { { 0, 1, 1, 1, 0 }, { 1, 0, 1, 0, 1 }, { 1, 1, 0, 1, 0 },
				{ 1, 0, 1, 0, 1 }, { 0, 1, 0, 1, 0 } };

		Hamilton p;
		p = new Hamilton(c, 5, 1);
		General.backtrack(p);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值