Link: http://oj.leetcode.com/problems/n-queens/
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.."] ]
1 public class Solution { 2 3 public ArrayList<String[]> result = new ArrayList<String[]>(); 4 5 public ArrayList<String[]> solveNQueens(int n) { 6 if (n < 1) 7 return null; 8 result = new ArrayList<String[]>(); 9 int[] queens = new int[n + 1]; 10 for (int i = 1; i <= n; i++) { 11 queens[1] = i; 12 dfs(2, n, queens); 13 } 14 return result; 15 } 16 17 public void dfs(int row, int size, int[] queens) { 18 if (row > size) { 19 print_queen(size,queens); 20 return; 21 } 22 for (int i = 1; i <= size; i++) { 23 if (isValid(row, i, queens)) { 24 queens[row] = i; 25 dfs(row + 1, size, queens); 26 queens[row] = 0; 27 28 } 29 } 30 } 31 32 public boolean isValid(int row, int col, int[] queens) { 33 for (int i = 1; i < row; i++) { 34 if (queens[i] != 0 35 && (queens[i] == col || (Math.abs(i - row) == Math 36 .abs(queens[i] - col)))) { 37 return false; 38 } 39 } 40 41 return true; 42 } 43 public void print_queen(int size,int[] queens) { 44 String[] str = new String[size]; 45 for (int i = 1; i <=size; i++) { 46 int temp = queens[i]; 47 String s = ""; 48 for (int j = 0; j < size; j++) { 49 if (j + 1 == temp) { 50 s += "Q"; 51 continue; 52 } 53 s += "."; 54 } 55 str[i - 1] = s; 56 } 57 result.add(str); 58 } 59 }