问题: 将n个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击,给你一个整数n,返回所有不同的n皇后问题的解决方案
1.1<=n<=9
2.该方案中 ‘Q’ 和 ‘.’ 分别代表了皇后和空位
3.皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行,纵行或斜线上
def gen_board(n, queens):
result = []
rows = ["."] * n
for i in range(n):
rows[queens[i]] = "Q"
result.append("".join(rows))
rows[queens[i]] = "."
return result
def back_track(line_num, n, queens, solutions, columns, diagonal1, diagonal2):
if line_num == n:
result = gen_board(n, queens)
solutions.append(result)
return
for i in range(n):
if i in columns or line_num - i in diagonal1 or line_num + i in diagonal2:
continue
queens[line_num] = i
columns.add(i)
diagonal1.add(line_num - i)
diagonal2.add(line_num + i)
back_track(line_num + 1, n, queens, solutions, columns, diagonal1, diagonal2)
columns.remove(i)
diagonal1.remove(line_num - i)
diagonal2.remove(line_num + i)
def solve_n_queens(n):
solutions = []
queens = [-1] * n
# 判断是否在一列
columns = set()
# 左斜线(左斜线上的每个值 横坐标减纵坐标 相等)
diagonal1 = set()
# 右斜线(右斜线上的每个值 横坐标加纵坐标 相等)
diagonal2 = set()
back_track(0, n, queens, solutions, columns, diagonal1, diagonal2)
return solutions
if __name__ == '__main__':
a = solve_n_queens(4)
print(len(a))
for x in a:
print("*" * 20)
for y in x:
print(y)