九皇后

import org.junit.Test;
//回溯法求解
public class QueenFind {

	public static final int N = 8;
	public static int count = 0;

	@Test
	public void test() {
		int[][] arr = new int[8][8];
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				arr[i][j] = 0;
			}
		}
		findQueen(0, arr);
		System.out.println("count" + count);

	}

	public void findQueen(int row, int[][] arr) {
		if (row == N) {
			count++;
			System.out.println("count" + count);
			return;
		}
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				arr[row][j] = 0;
			}
			arr[row][i] = 1;
			for (int k = 0; k < N; k++) {
				System.out.print(arr[row][k] + " ");
			}
			System.out.println();
			System.out.println(row);
			if (isSafety(arr, row, i)) {
				findQueen(row + 1, arr);
			}
		}
	}

	private boolean isSafety(int[][] chess, int row, int col) {
		// 判断中上、左上、右上是否安全
		int step = 1;
		while (row - step >= 0) {
			if (chess[row - step][col] == 1) // 中上
				return false;
			if (col - step >= 0 && chess[row - step][col - step] == 1) // 左上
				return false;
			if (col + step < N && chess[row - step][col + step] == 1) // 右上
				return false;

			step++;
		}
		return true;
	}
}

posted @ 2018-04-08 16:05  wei1  阅读(164)  评论(0)    收藏  举报