N皇后问题(python实现)

N皇后问题

n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击。

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

每个解决方案包含一个明确的n皇后放置布局,其中“Q”和“.”分别表示一个女王和一个空位置。

样例

对于4皇后问题存在两种解决的方案:

[

[".Q..", // Solution 1

 "...Q",

 "Q...",

 "..Q."],

["..Q.", // Solution 2

 "Q...",

 "...Q",

 ".Q.."]

 ]

思路

由于每行只能有一个皇后,第一行 有N种可能,从一行一列开始 如果一行一列可以放置皇后 则找到下一行第一个能放置皇后的列。如果下一行 没有符合条件的列,就返回上一行找到下一个可以放置皇后的列。遍历的行数 == N 则获得一次 结果。如果在第一行也找不到能放置皇后的列 则查找结束。

实现

循环实现

class Solution:
    """
    Get all distinct N-Queen solutions
    @param n: The number of queens
    @return: All distinct solutions
    """
    def solveNQueens(self, n):
        # write your code here
        #每一行和每一列只能有一个皇后 而且必定有一个皇后
        n = int(n)
        result = []
        col = [-1]*n
        k = 0
        #row
        while k>=0:
            #查看下一列    
            col[k] = col[k]+1
            while col[k]and not self.judgePlace(k,col):
                #col
                col[k] += 1
            if col[k]#获得一次解
                if k == n-1:
                    empty = ['.'*n for i in range(0,n)]
                    for i in range(0,n):
                        temp = list(empty[i])
                        temp[col[i]] = 'Q'
                        empty[i] = ''.join(temp)
                    result.append(empty)
                #判断下一行
                else:
                    k +=1
                    #清除残留数据
                    col[k] = -1
            #没有找到结果回溯        
            else:
                k -= 1


        return result

    def judgePlace(self,k,col):
        for i in range(0,k):
            if col[i] == col[k] or (abs(col[k]-col[i]) == abs(k - i)):
                return False
        return True

递归实现

class Solution:
    """
    Get all distinct N-Queen solutions
    @param n: The number of queens
    @return: All distinct solutions
    """
    def solveNQueens(self, n):
        n = int(n)
        result = []
        record = [0]*(n+1)
        self.findResult(result,n,1,1,record)
        return result


    def findResult(self,result,total,row,col,record):
        if row == 0:
            return result
        record[row] = col
        while record[row]<=total and not self.judgePlace(row,record):
            record[row] += 1
        #回溯    
        if record[row]>total:
            row -= 1
            newCol = record[row] + 1
            self.findResult(result,total,row,newCol,record)
        else:
            if row == total:
                empty = ['.'*total for i in range(0,total)]
                for i in range(0,total):
                    temp = list(empty[i])
                    temp[record[i+1]-1] = 'Q'
                    empty[i] = ''.join(temp)
                result.append(empty)
                #回溯
                row -= 1
                newCol = record[row] + 1
                self.findResult(result,total,row,newCol,record)
            else:
                row += 1
                self.findResult(result,total,row,1,record)



    def judgePlace(self,row,col):
        for i in range(1,row):
            if col[i] == col[row] or (abs(col[row]-col[i]) == abs(row - i)):
                return False
        return True

你可能感兴趣的:(python)