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.

N-Queens - 图1

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:

  1. [
  2. [".Q..", // Solution 1
  3. "...Q",
  4. "Q...",
  5. "..Q."],
  6. ["..Q.", // Solution 2
  7. "Q...",
  8. "...Q",
  9. ".Q.."]
  10. ]

Solution:

  1. public class Solution {
  2. public List<String[]> solveNQueens(int n) {
  3. List<String[]> res = new ArrayList<String[]>();
  4. helper(n, 0, new int[n], res);
  5. return res;
  6. }
  7. private void helper(int n, int row, int[] columnForRow, List<String[]> res) {
  8. if (row == n) {
  9. String[] sol = new String[n];
  10. for (int r = 0; r < n; r++) {
  11. sol[r] = "";
  12. for (int c = 0; c < n; c++) {
  13. sol[r] += (columnForRow[r] == c) ? "Q" : ".";
  14. }
  15. }
  16. res.add(sol);
  17. return;
  18. }
  19. for (int col = 0; col < n; col++) {
  20. columnForRow[row] = col;
  21. if (check(row, col, columnForRow)) {
  22. helper(n, row + 1, columnForRow, res);
  23. }
  24. }
  25. }
  26. private boolean check(int row, int col, int[] columnForRow) {
  27. for (int r = 0; r < row; r++) {
  28. if (columnForRow[r] == col || row - r == Math.abs(columnForRow[r] - col)) {
  29. return false;
  30. }
  31. }
  32. return true;
  33. }
  34. }