45行python代码实现皇后问题

import copy
class Queen:
    def __init__(self, n):
        self.n=n

    def get_empty(self):
        return [[0 for i in range(self.n)] for i in range(self.n)]

    def display(self,v):
        for i in v:
            print i
        print

    def put_queen(self,v,x,y):
        if v[x][y]!=0: return 0
        for i in range(self.n):
            if(i!=y): v[x][i]=1
            if(i!=x): v[i][y]=1
            dx=x-i
            if 0 <= y-dx < self.n  :
                v[i][y-dx]=1
            if 0 <= y+dx < self.n  :
                v[i][y+dx]=1
        v[x][y]=2
        return 1

    def solute(self):
        for i in range(self.n):
            temp=self.get_empty()
            self.put_queen(temp,0, i)
            self.do_row(temp,1)
    
    def do_row(self, v, index):
        i=0
        while i            temp=copy.deepcopy(v)
            if self.put_queen(temp,index, i):
                if index == self.n-1:
                    self.display(temp)
                    return 1
                self.do_row(temp, index+1)                  
            i+=1
        return 0
   
Queen(8).solute()

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.