zoukankan      html  css  js  c++  java
  • LeetCode 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;  
     3     int[] A;  
     4     public List<String[]> solveNQueens(int n) {  
     5         result = new ArrayList<String[]>();  
     6         A = new int[n];  
     7         nqueens(0, n);  
     8         return result;  
     9     }  
    10     public void nqueens(int cur, int n){  
    11         if(cur==n) printres(n);  
    12         else {  
    13             for(int i=0;i<n;i++){  
    14                 A[cur] = i;  
    15                 if(valid(cur)){  
    16                     nqueens(cur+1, n);  
    17                 }  
    18             }  
    19         }  
    20     }  
    21     public void printres(int n){  
    22         String[] tem = new String[n];  
    23         for(int i=0;i<n;i++){  
    24             StringBuffer sBuffer = new StringBuffer();  
    25             for(int j=0;j<n;j++){  
    26                 if(j==A[i]) sBuffer.append('Q');  
    27                 else sBuffer.append('.');  
    28             }  
    29             tem[i] = sBuffer.toString();  
    30         }  
    31         result.add(tem);  
    32     }  
    33     public boolean valid(int r){  
    34         for(int i=0;i<r;i++){  
    35             if(A[i]==A[r]|| Math.abs(A[i]-A[r])==r-i){  
    36                 return false;  
    37             }  
    38         }  
    39         return true;  
    40     }  
    41 }
  • 相关阅读:
    分布式锁-数据库实现
    MyBatis-Plus自动填充功能失效导致原因
    Java中锁的解决方案
    2:什么是单体应用锁?什么是分布式锁?
    1:初始锁这个概念
    移动端网页开发问题小结
    node.js+socket.io创建web聊天室
    使用HTML5实现刮刮卡效果
    总结(活动)
    videoJs 使用
  • 原文地址:https://www.cnblogs.com/birdhack/p/4243032.html
Copyright © 2011-2022 走看看