leetcode--51. N皇后

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hilavergil/article/details/80670827

题目:51. N皇后

链接:https://leetcode-cn.com/problems/n-queens/description/

给出N皇后的所有解。

还是用了DFS,怎么优化也给忘了,原地踏步。

python:

class Solution(object):
    def solveNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        def isPosLegal(x,y,n):
            return x>=0 and x<n and y>=0 and y<n
        def isLegal(x,y,n,field):
            if "Q" in field[x]:
                return False
            for r in range(n):
                if field[r][y]=="Q":
                    return False
            xtmp,ytmp=x,y
            while isPosLegal(xtmp,ytmp,n):
                if field[xtmp][ytmp]=="Q":
                    return False
                xtmp-=1
                ytmp-=1
            xtmp, ytmp = x, y
            while isPosLegal(xtmp,ytmp,n):
                if field[xtmp][ytmp]=="Q":
                    return False
                xtmp-=1
                ytmp+=1
            xtmp, ytmp = x, y
            while isPosLegal(xtmp,ytmp,n):
                if field[xtmp][ytmp]=="Q":
                    return False
                xtmp+=1
                ytmp-=1
            xtmp, ytmp = x, y
            while isPosLegal(xtmp,ytmp,n):
                if field[xtmp][ytmp]=="Q":
                    return False
                xtmp+=1
                ytmp+=1
            return True
        field=[["." for i in range(n)] for j in range(n)]
        def getMap(n,field):
            ret=[]
            for i in range(n):
                ret.append("".join(field[i]))
            return ret
        ret=[]
        def dfs(row,n,field):
            if row==n:
                ret.append(getMap(n, field))
                return
            for col in range(n):
                if isLegal(row,col,n,field):
                    field[row][col]="Q"
                    dfs(row+1,n,field)
                    field[row][col] = "."
        dfs(0,n,field)
        return ret

猜你喜欢

转载自blog.csdn.net/Hilavergil/article/details/80670827