zoukankan      html  css  js  c++  java
  • leetcode刷题-52N皇后2

    题目

    皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。给定一个整数 n,返回 n 皇后不同的解决方案的数量。

    思路

    与51题完全一致

    实现

    class Solution:
        def totalNQueens(self, n: int) -> int:
            table = [[False for _ in range(n)] for j in range(n)]
            result = [['.' for _ in range(n)] for j in range(n)]
            answer = 0
            checkflag = False
    
            def put(i, j):
                tmp = []
                tmp1 = i + j
                tmp2 = i - j
                for l in range(n):
                    for m in range(n):
                        if l == i or m == j or l + m == tmp1 or l - m == tmp2:
                            if table[l][m] == False:
                                table[l][m] = True
                                tmp.append((l, m))
                result[i][j] = "Q"
                return tmp
    
            def remove(i, j, tmp):
                for x in tmp:
                    l = x[0]
                    m = x[1]
                    table[l][m] = False
                result[i][j] = "."
    
            def valid(i, j):
                if table[i][j] is False:
                    return True
    
            def check(i, j):
                if i == n-1:
                    nonlocal answer
                    answer += 1
                    nonlocal checkflag
                    checkflag = True
                else:
                    for x in range(n):
                        backtrace(i + 1, x)
    
    
            def backtrace(row, col):
                #if result[row][col] == '.':
                if valid(row, col):
                    tmp = put(row, col)
                    check(row, col)
                    remove(row, col, tmp)
            
            for t in range(n):
                backtrace(0, t)
                checkflag = False
                table = [[False for _ in range(n)] for j in range(n)]
                result = [['.' for _ in range(n)] for j in range(n)]
            return answer
  • 相关阅读:
    Vue DatePicker和不可用
    API图片路径和超链接语义化转换
    jQuery常用插件大全
    前端面试必备技巧整理
    堆与堆排序/Heap&Heap sort
    第k大的数
    POJ 2083 Fractal 分形题目
    最大子数组问题/Maximum Subarray
    一个简单的随机数生成算法
    成绩排序
  • 原文地址:https://www.cnblogs.com/mgdzy/p/13432596.html
Copyright © 2011-2022 走看看