zoukankan      html  css  js  c++  java
  • 51. N-Queens java solutions

    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     public List<List<String>> solveNQueens(int n) {
     3         List<List<String>> ans = new ArrayList<List<String>>();
     4         recursive(ans,new int[n],0,n);
     5         return ans;
     6     }
     7     
     8     public void recursive(List<List<String>> ans,int[] columnForRow,int row,int n){
     9         if(row == n){
    10             List<String> tmp = new ArrayList<String>();
    11             for(int i = 0;i < n;i++){
    12                 StringBuilder sb = new StringBuilder();
    13                 for(int j = 0;j < n;j++){
    14                     if(columnForRow[i] == j)
    15                         sb.append("Q");
    16                     else 
    17                         sb.append(".");
    18                 }
    19                 tmp.add(sb.toString());
    20             }
    21             ans.add(tmp);
    22             return;
    23         }
    24         
    25         for(int i = 0; i < n; i++){
    26             columnForRow[row] = i;
    27             if(check(columnForRow,row)){
    28                 recursive(ans,columnForRow,row+1,n);//递归回溯
    29             }
    30         }
    31     }
    32     
    33     public boolean check(int[] columnForRow, int row){
    34         for(int i = 0; i < row; i++){
    35             if(columnForRow[row] == columnForRow[i] || row-i == Math.abs(columnForRow[row] - columnForRow[i]))
    36                 return false;//检查其他行有列相同或者,对角线有没有元素就是行差和列差不要相同
    37         }
    38         return true;
    39     }
    40 }
  • 相关阅读:
    Linux平台下基于图像识别的自动化测试-sikuli环境搭建
    从命令行运行SikuliX
    Linux命令grep过滤的用法
    PyCharm注释头模板
    从BeautifulReport生成的html格式的测试报告中获取测试结果,并写入到一个表格中
    unittest在命令行中执行
    在Debian上安装Docker Engine
    Linux平台UI自动化测试-环境搭建
    python标准库smtplib在UI自动化测试中的实现-邮件发送测试报告
    wget cooikes 下载
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5623093.html
Copyright © 2011-2022 走看看