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

}
 

你可能感兴趣的:(UE)