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 }
    
    
  • 相关阅读:
    DOM节点的删除(jQuery)
    DOM节点的插入(jQuery)
    DOM节点创建(jQuery)
    jQuery的属性及样式
    jQuery选择器
    jQuery对象及DOM对象
    给大家分享一个很好用的屏幕共享小软件
    Web单浏览器登录
    Winform制作圆弧panel
    Winform 无边框窗口移动自定义边框粗细颜色
  • 原文地址:https://www.cnblogs.com/huntfor/p/3843612.html
Copyright © 2011-2022 走看看