51. N-Queens

问题描述:

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

国际象棋中,Queen可以横向、纵向和沿着对角线行驶。我们要将N个Queen放置在nXn的棋盘上,满足:每行、每列都只有一个皇后;每一条对角线上(正or反)都不能有超过一个的皇后。该题目让我们对给定的N,求出所有的可行解。

解法:

方法出处:http://www.cnblogs.com/bigbigtree/p/3889591.html

import java.util.ArrayList;
import java.util.List;

/**
 * N-皇后问题
 * @author Administrator
 *
 */
public class Solution {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int n = 4;
		System.out.println(new Solution().solveNQueens(n));
	}
	
	private List<List<String>> res = new ArrayList<List<String>>();//存放结果
	
	public List<List<String>> solveNQueens(int n) {
        int[] q = new int[n+1];//数组:存放每一个x值上的皇后位置(倘若(1,2)上有皇后,则q[1]=2;倘若x=1还没有放置皇后,则q[1]=0)
        n_queens(q,1);
		return res;
    }
	
	/**
	 * 验证一个位置(x,y)是否可放置
	 * @param q
	 * @param x
	 * @param y
	 * @return
	 */
	private boolean isValid(int[] q,int x,int y){
		int n = q.length - 1;
		for(int i = 1; i <= n; i++){//x轴从1到n遍历,看是否合法
			int yq = q[i];
			if(yq == y)//y值冲突
				return false;
			if(yq != 0 && yq + i == x + y)//反对角线冲突
				return false;
			if(yq != 0 && yq - i == y - x)//正对角线冲突
				return false;
		}
		return true;
	}
	
	/**
	 * 放置x轴的值为curX上的皇后
	 * @param q
	 * @param curX
	 */
	private void n_queens(int[] q,int curX){
		int n = q.length - 1;
		for(int i = 1; i <= n; i++){//y值从1到n都要试一次
			if(isValid(q,curX,i)){
				q[curX] = i;//(curX,i)处放置皇后
				if(curX == n){//正在处理的是最后一个x值
					genResult(q);
					q[curX] = 0;//皇后位置归零
					return;
				}
				n_queens(q,curX+1);//放置下一个x值上的皇后
				q[curX] = 0;//皇后位置归零
			}
		}
	}
	
	/**
	 * 根据q数组生成结果
	 * @param q
	 */
	private void genResult(int[] q){
		int n = q.length - 1;
		List<String> list = new ArrayList<String>();
		for(int i = 1; i <= n; i++){
			int yq = q[i];
			String temp = "";
			for(int j=1; j <= n; j++){
				if(j == yq){
					temp += 'Q';
				}
				else{
					temp += '.';
				}
			}
			list.add(temp);
		}
		res.add(list);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值