# coding=utf-8
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
class Solution(object):
def EightQueen(self):
def Qualified(deepth, y):#判断棋子位置是否合适
for queen in stack_curr:
if queen[1]==y or abs(queen[0]-deepth)==abs(queen[1]-y):
return False
return True
stack_re = []#结果栈
stack_curr = []#临时栈
def dfs(deepth=1):
if deepth==9:
stack_re.append(''.join('%s' % id for id in stack_curr))
else:
for i in range(1,9):#i其实是棋子纵坐标
if Qualified(deepth,i)==True:
stack_curr.append([deepth,i])#压栈
dfs(deepth+1)#递归
stack_curr.pop()#弹栈
else:#这里不能pop,走不动就没有返回值,自己溜掉了,函数会自动回溯上一个结点的栈帧,应该算是自动剪枝?
pass
dfs()
return stack_re
a=Solution()
queen_answer=a.EightQueen()
print len(queen_answer),queen_answer
讲道理,今天看了力扣17题,自己默写了dfs的回溯算法,然后又自己写了八皇后,还跑起来了,成就感满满