51. 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:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

深度优先的思想,如果当前位置与其他位置相互攻击,则减掉该节点,然后回溯。




 1 public class Solution {
 2     private List<List<String>> res = new ArrayList<List<String>>();
 3     public List<List<String>> solveNQueens(int n) {
 4         char[][] board = new char[n][n];
 5         for(int i = 0; i < n; i++)
 6             for(int j = 0; j < n; j++)
 7                 board[i][j] = '.';
 8         dfs(board, 0);
 9         return res;
10     }
11     
12     private void dfs(char[][] board, int col) {
13         if(col==board.length){
14             res.add(construct(board));
15             return;
16         }
17         for(int i = 0;i<board.length;i++){
18             if(validate(board,i,col)){
19             board[i][col] = 'Q';
20             dfs(board,col+1);
21             board[i][col] = '.';
22             }
23         }
24     }
25     
26     private boolean validate(char[][] board, int x, int y) {
27        for(int i = 0;i<board.length;i++)
28            for(int j = 0;j<y;j++)
29                if(board[i][j]=='Q'&&(x==i||x+j==y+i||x+y==i+j))
30                    return false;
31         return true;
32     }
33     
34     private List<String> construct(char[][] board) {
35         List<String> res = new ArrayList<String>();
36         for(int i = 0; i < board.length; i++) {
37             String s = new String(board[i]);
38             res.add(s);
39         }
40         return res;
41     }
42 }
原文地址:https://www.cnblogs.com/zle1992/p/8915628.html