`
hcx2013
  • 浏览: 83035 次
社区版块
存档分类
最新评论

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


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;
    }

}
 
0
9
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics