Recursive backtracking - eight queens problem

Eight queens problem:

     Chess queens can horizontal, vertical and angular movement of the other pieces of the three lines that can be eaten. The so-called eight queens problem is this: the eight queens on a 8x8 board, so that each can not eat anything else Queens Queens, (that is, any two Queen's not in the same straight horizontal, vertical and diagonal ), asked a total of how many pendulum method?

Solution:
1. Add the first row and first column
2. In the second row a suitable location (not on a peer-queen same column, and diagonal) placed
so forth until the eighth into Queen i.e. as a solution, if not to the Queen on the eighth to fall back on a line change and then continue into the

Let's look at the code:

public class EightQueen {
	// 棋盘,放皇后
	public static int[][] arry = new int[8][8];
	// 存储方案结果数量
	public static int count = 0;

	public static void main(String[] args) {
		System.out.println("八皇后问题");
		findQueen(0);
		System.out.println("八皇后问题共有:" + count + "种可能");
	}

	// 寻找皇后节点
	public static void findQueen(int i) {
		// 八皇后的解
		if (i > 7) {
			count++;
			// 打印八皇后的解
			print();
			return;
		}
		// 深度回溯,递归算法
		for (int m = 0; m < 8; m++) {
			// 检查皇后摆放是否合适
			if (check(i, m)) {
				arry[i][m] = 1;
				findQueen(i + 1);
				// 清零,以免回溯的时候出现脏数据
				arry[i][m] = 0;
			}
		}
	}

	// 判断节点是否合适
	public static boolean check(int k, int j) {
		// 检查行列冲突
		for (int i = 0; i < 8; i++) {
			if (arry[i][j] == 1) {
				return false;
			}
		}
		// 检查左对角线
		for (int i = k - 1, m = j - 1; i >= 0 && m >= 0; i--, m--) {
			if (arry[i][m] == 1) {
				return false;
			}
		}
		// 检查右对角线
		for (int i = k - 1, m = j + 1; i >= 0 && m <= 7; i--, m++) {
			if (arry[i][m] == 1) {
				return false;
			}
		}
		return true;
	}

	// 打印结果
	public static void print() {
		System.out.println("方案" + count + ":");
		for (int i = 0; i < 8; i++) {
			for (int m = 0; m < 8; m++) {
				if (arry[i][m] == 1) {
					System.out.print("Q ");
				} else {
					System.out.print("+ ");
				}
			}
			System.out.println();
		}
		System.out.println();
	}
}

 

Guess you like

Origin blog.csdn.net/sinat_22808389/article/details/94388500