• Leetcode 51.N后问题


    N后问题

    皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

    上图为 8 皇后问题的一种解法。

    给定一个整数 n,返回所有不同的 皇后问题的解决方案。

    每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。

    示例:

    输入: 4

    输出: [

    [".Q..", // 解法 1

    "...Q",

    "Q...",

    "..Q."],

    ["..Q.", // 解法 2

    "Q...",

    "...Q",

    ".Q.."]

    ]

    解释: 4 皇后问题存在两个不同的解法。

     1 import java.util.*;
     2 
     3 public class Solution{
     4     public List<List<String>> solveNQueens(int n){
     5         List<List<String>> res=new ArrayList<List<String>>();
     6         int[] queenList=new int[n];//第i个位置存放的数表示row行时,Q的列
     7         placeQueen(queenList,0,n,res);//在第0行放Q
     8         return res;
     9     }
    10 
    11     private void placeQueen(int[] queenList,int row,int n,List<List<String>> res){
    12         if(row==n){
    13             ArrayList<String> list=new ArrayList<String>();
    14             for(int i=0;i<n;i++){
    15                 String str="";
    16                 for(int col=0;col<n;col++){
    17                     if(queenList[i]==col){
    18                         str+="Q";
    19                     }else{
    20                         str+=".";
    21                     }
    22                 }
    23                 list.add(str);
    24             }
    25             res.add(list);
    26         }
    27         for(int col=0;col<n;col++){
    28             if(isValid(queenList,row,col)){
    29                 queenList[row]=col;
    30                 placeQueen(queenList,row+1,n,res);
    31             }
    32         }
    33     }
    34 
    35     private boolean isValid(int[] queenList,int row,int col){
    36         for(int i=0;i<row;i++){
    37             int pos=queenList[i];
    38             if(pos==col)
    39                 return false;
    40             if(pos+row-i==col)
    41                 return false;
    42             if(pos-row+i==col)
    43                 return false;
    44         }
    45         return true;
    46     }
    47 }
  • 相关阅读:
    接口详解
    可空类型
    初学泛型
    结构和类
    触发器
    学习C#异常处理机制
    静飘移
    《Hashtable(散列表)》 集合
    自定义集合类
    Automation伺服程式無法産生物件
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10163030.html
Copyright © 2020-2023  润新知