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 }
    
    
  • 相关阅读:
    Vue 框架怎么实现对象和数组的监听?
    能说下 vue-router 中常用的 hash 和 history 路由模式实现原理吗?
    vue-router 路由模式有几种?
    Vue 组件间通信有哪几种方式?
    v-model 的原理?
    华硕笔记本修复
    linux下制作u盘启动盘
    virtualbox不能启动虚拟机
    ubuntu14.04建立wifi热点
    git中文文件名和中文目录显示乱码
  • 原文地址:https://www.cnblogs.com/huntfor/p/3843612.html
Copyright © 2011-2022 走看看