zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    第八届极客大挑战 Web-php绕过
    第八届极客大挑战 Web-故道白云&Clound的错误
    IMDB-TOP_250-爬虫
    任意角度图片旋转
    图片处理代码
    C#获取获取北京时间多种方法
    STL vector用法介绍
    C++ 用libcurl库进行http通讯网络编程
    CString 使用方法
    A星算法(游戏寻路算法)的C++实现(转)
  • 原文地址:https://www.cnblogs.com/zle1992/p/8915628.html
Copyright © 2011-2022 走看看