lintcode-medium-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.
Example
There exist two distinct solutions to the 4-queens puzzle:
[
// Solution 1
[".Q..",
"...Q",
"Q...",
"..Q."
],
// Solution 2
["..Q.",
"Q...",
"...Q",
".Q.."
]
]
Challenge
Can you do it without recursion?
class Solution { /** * Get all distinct N-Queen solutions * @param n: The number of queens * @return: All distinct solutions * For example, A string '...Q' shows a queen on forth position */ ArrayList<ArrayList<String>> solveNQueens(int n) { // write your code here ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>(); if(n <= 0) return result; int[] position = new int[n]; helper(result, 0, position, n); return result; } public void helper(ArrayList<ArrayList<String>> result, int row, int[] position, int n){ if(row == n){ ArrayList<String> solution = new ArrayList<String>(); for(int i = 0; i < n; i++){ StringBuilder line = new StringBuilder(); for(int j = 0; j < n; j++){ if(j == position[i]) line.append('Q'); else line.append('.'); } solution.add(line.toString()); } result.add(new ArrayList<String>(solution)); return; } for(int i = 0; i < n; i++){ position[row] = i; if(valid(position, row, n)) helper(result, row + 1, position, n); } return; } public boolean valid(int[] position, int row, int n){ for(int i = row - 1; i >= 0; i--){ if(position[row] == position[i] || Math.abs(position[row] - position[i]) == row - i) return false; } return true; } };