首页 > 其他 > 详细

N-Queens

时间:2015-06-20 02:06:15      阅读:265      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣

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.."]
]


public class Solution {
    public List<String[]> solveNQueens(int n) {
    	List<String[]> res = new ArrayList<String[]>();
    	solve(0, n, new int[n], res);
    	return res;
    }

	private void solve(int i, int n, int[] positions,
            List<String[]> list) {
		if (i == n) {
			String[] result = new String[n];
			for (int k = 0; k < n; k++) {
	            StringBuffer sb = new StringBuffer();
	            for (int j = 0; j < n; j++) {
	                if (j == positions[k])
	                    sb.append(‘Q‘);
	                else
	                    sb.append(‘.‘);
	            }
	             
	            result[k] = sb.toString();
	        }
	        list.add(result);
		} else {
			for (int j = 0; j < n; j++) {
				positions[i] = j;
				if (validate(i, positions)) {
					solve(i+1, n, positions, list);
				}
			}
		}
	}
	private boolean validate(int maxRow, int[] positions) {
        for (int i = 0; i < maxRow; i++) {
            if (positions[i] == positions[maxRow]
                    || Math.abs(positions[i] - positions[maxRow]) == maxRow - i) 
                return false;
        }
         
        return true;
    }

}
?

N-Queens

原文:http://hcx2013.iteye.com/blog/2220836

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!