借着
python解八皇后问题(一) 研究一下栈溢出问题。
pycharm里栈溢出报错是:
Process finished with exit code -1073741571 (0xC00000FD)
linux栈溢出报错是:
Segmentation fault (core dumped)
改造了一下函数:
def eight_quene(x=0, y=0):
# print(x, y)
global stacks
# print(stacks)
stacks += 1
if y == n:
if x == 1:
print('finished')
print(stacks)
return
else:
x -= 1
y = board[x].index(1)
board[x][y] = 0
# print('y==n and x !=0')
eight_quene(x, y+1)
else:
if allow_luozi(x, y):
board[x][y] = 1
if x == n - 1:
global count
count += 1
print(count)
for line in board:
print(line)
print()
board[x][y] = 0
x -= 1
y = board[x].index(1)
board[x][y] = 0
eight_quene(x, y+1)
else:
# print('luozi and next row')
eight_quene(x+1, 0)
else:
# print('not luozi and next column')
eight_quene(x, y+1)
for i in range(n):
eight_quene(0,i)
board = [[0 for _ in range(n)] for _ in range(n)]
print(stacks)
循环执行8次,每次固定第一行皇后的位置,递归解下面7行皇后的位置,成功完成,总共递归了17271次。
测了一遍递归栈容量:
OS | default | sys.setrecursionlimit(100000) |
---|---|---|
win | 996 | 2512 |
linux | 998 | 16361 |
linux默认递归栈容量是8M,可以通过ulimit -s
扩充。