21 April 2015

回溯算法的核心思想:当进行到某一步时,发现先前的选择并不好或达不到目标,就退回一步重新选择。

熟悉一下java的语法以及在eclipse中的调试和运行。
注意:windows下要在Administor的用户变量PATH后面加上C:\Program Files\Java\jdk1.8.0_25\bin
      主文件名和类名必须相同,这里都是test
测试文件: test.java   
public class test
{
	public static void main(String args[]) {
		System.out.println("Hello world!");
	}
}
D:\>javac test.java   编译生成test.class
D:\>java test         执行test.class,此处不要加后缀.class,否则会出现找不到主类的错误
Hello world!
import java.lang.Math;
import java.util.Scanner;

public class test {
	static Scanner scan;
	static int N ;
	static int x[];
	static int total;
	
	static void printBoard() {
		System.out.println(total);
		for (int t = 1; t <= N; t++) {
			for (int j = 1; j <= N; j++) {
				if (x[t] == j) {
					System.out.print("Q ");
				} else {
					System.out.print(". ");
				}
			}
			System.out.print("\n");
		}
		System.out.print("\n");
	}
	
	static boolean Place(int k) {
		for (int j = 1; j < k; j++)
			if ( Math.abs(k - j)==Math.abs(x[j]-x[k]) || x[j] == x[k] )
				return false;
		return true;
	}

	static void Backtrak(int t) {
		if (t > N) {
			total++;
		    printBoard();
		} else
			for (int i = 1; i <= N; i++) 
			{
				x[t] = i;
				if (Place(t)) Backtrak(t + 1);
			}
	}
	
	public static void main(String args[]) {
		scan=new Scanner(System.in);
		System.out.println("The value of N is :");
		N=scan.nextInt();
		x=new int[N+1];
		total = 0;
		for(int i = 0; i <= N; i++) x[i] = 0;
		Backtrak(1);
	}
}


blog comments powered by Disqus