zoukankan      html  css  js  c++  java
  • [leetcode]N-Queens

    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 }
    
    
  • 相关阅读:
    Java线程专题 3:java内存模型
    Java线程专题 2:synchronized理解
    Java线程专题 1:线程创建
    设计模式七大原则
    JVM 运行时数据区
    css_selector定位,比xpath速度快,语法简洁
    xpath绝对定位和相对定位
    selenium多种定位
    操作浏览器基本元素(不定时更新)
    爬取网页图片并且下载(1)
  • 原文地址:https://www.cnblogs.com/huntfor/p/3843612.html
Copyright © 2011-2022 走看看