N皇后问题(函数式编程与过程式)

1.Haskell

safe :: Int -> [Int] -> Int -> Bool
safe _ [] _ = True
safe x (x1:xs) n = 
    x /= x1 
    && x /= x1 + n && x /= x1 - n
    && safe x xs (n+1)

queenN :: Int -> [[Int]]
queenN 0 = [[]]
queenN n = [x : y | y <- queenN(n-1) , x <- [1..8],safe x y 1]

safe 判断和自己n行前的那个有没有冲突,x1 + 1,x1 - 1表示右上角和左上角

2. python

class Solution:
    def solveNQueens(self, n: int) -> List[List[int]]:
        c = [False] * n
        l1 = [False] * (2 * n)
        l2 = [False] * (2 * n)
        ans = []
        l = []
        def is_attacted(i: int, j: int) -> bool:
            # 对角线 j-i+n 相同为同一对角线,j+i相同为同一副对角线
            return True if c[j] or l1[j - i + n] or l2[j + i] else False

        def add_queen(i, j):
            c[j] = not c[j]
            l1[j - i + n] = not l1[j - i + n]
            l2[j + i] = not l2[j + i]

        def remove_queen(i, j):
            add_queen(i,j)

        def bt (i):
            if i == n :
                ans.append(l.copy())
            for x in range(n):
                if not is_attacted(i,x):
                    l.append(x)
                    add_queen(i,x)
                    bt(i+1)
                    remove_queen(i,x)
                    l.pop()
        bt(0)

        return ans

s = Solution()
print(s.solveNQueens(4))

 

posted @ 2020-02-12 10:52  式微胡不归  阅读(238)  评论(0编辑  收藏  举报