LeetCode-52 N-Queens II

Description

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 the number of distinct solutions to the n-queens puzzle.

Example

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q…", // Solution 1
“…Q”,
“Q…”,
“…Q.”],

["…Q.", // Solution 2
“Q…”,
“…Q”,
“.Q…”]
]

Submissions

首先这道题要求给定一个整数 n,返回 n 皇后不同的解决方案的数量,题目基本与上一题相同,所以重点解题思路可看上篇博客,同理这道题解题思路一样采用DFS深度优先遍历,一次深度查找直到最后一个满足或不满足条件的位置,回溯。其中遍历n代表遍历皇后的横坐标,col存储的是皇后的纵坐标,dia存储皇后的横纵坐标差,codia存储皇后的横纵坐标和。确定皇后横坐标开始深度优先遍历纵坐标,满足位置条件时则更新col,dia,codia三个列表以判断下一位置是否符合条件,当遍历到一定深度无解时则遍历下一横坐标,最后将有效解存储到rel列表中并返回结果个数。

实现代码如下:

class Solution:
    def totalNQueens(self, n: int) -> int:
        if n==0:
            return []
        self.rel = []
        col = []
        dia = []
        codia = []
        self.DFS(n,col,dia,codia)
        return len(self.rel)
    
    def DFS(self,n,col,dia,codia):
        x = len(col)
        if x == n:
            self.rel.append(col)
            return None
        for y in range(n):
            if y not in col and x-y not in dia and x+y not in codia:
                self.DFS(n,col+[y],dia+[x-y],codia+[x+y])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值