[leetcode]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.."] ]
算法思路:
回溯算法,经典的八皇后问题,不多啰嗦,不明白的请戳这里;
1 public class Solution { 2 List<String[]> result = new ArrayList<String[]>(); 3 public List<String[]> solveNQueens(int n) { 4 if(n <= 0) return result; 5 int[] hash = new int[n]; 6 dfs(hash,0,n); 7 return result; 8 } 9 private void dfs(int[] hash,int row,int n){ 10 if(row == n ){ 11 String[] node = new String[n]; 12 for(int i = 0; i < n; i++){ 13 StringBuilder sb = new StringBuilder(); 14 for(int j = 0; j < n;sb.append('.'),j++); 15 sb.setCharAt(hash[i], 'Q'); 16 node[i] = sb.toString(); 17 } 18 result.add(node); 19 } 20 for(int i = 0; i < n; i++){ 21 if(!isConflict(hash, row, i)){ 22 hash[row] = i; 23 dfs(hash, row + 1, n); 24 hash[row] = 0;//track back 25 } 26 } 27 } 28 private boolean isConflict(int[] hash,int row,int column){ 29 for(int i = 0; i < row; i++){ 30 if(hash[i] == column) return true; 31 else if(i - hash[i] == row - column || hash[i] + i == row + column) return true; 32 } 33 return false; 34 } 35 }