# 回溯算法-八皇后问题

8x8棋盘摆8个皇后，使得不能相互攻击（不在同一行、列、斜线上）。求多少种摆法

```python
n=8
x=[] #当前尝试方案
X=[] #所有可行方案
def conflict(k):
    global x
    for i in range(k):#遍历前0 - k-1
        # 判断是否与x[k]冲突
        if x[i]==x[k] or abs(x[i]-x[k])==abs(i-k):
            return True
    return False

def queens(k):#到达第k行，进行判断
    global n,x,X
    if k>=n:#如果到底部，那就是一个解，添加进去，因为到底部，意味着不与面前所有皇后冲突
#         print(x)
        X.append(x[:])
    else:#否则继续往下走，走的地方有n个，依次尝试
        for i in range(n):
            x.append(i)
            if not conflict(k):#不冲突，就继续往下走
                queens(k+1)#到k+1行进行判断
            #无论怎样，回溯，退回上一步尝试的位置，尝试其它位置
            x.pop()

def show(x):
    global n
    for i in range(n):
        print('. '*(x[i])+'X '+'. '*(n-x[i]-1))

queens(0)
print(X[-1],'\n')
show(X[-1])
print('-'*50)
print(X[-2],'\n')
show(X[-2])
```

```
[7, 3, 0, 2, 5, 1, 6, 4] 

. . . . . . . X 
. . . X . . . . 
X . . . . . . . 
. . X . . . . . 
. . . . . X . . 
. X . . . . . . 
. . . . . . X . 
. . . . X . . . 
--------------------------------------------------
[7, 2, 0, 5, 1, 4, 6, 3] 

. . . . . . . X 
. . X . . . . . 
X . . . . . . . 
. . . . . X . . 
. X . . . . . . 
. . . . X . . . 
. . . . . . X . 
. . . X . . . .
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/shua-ti/si-xiang-lei/hui-su/ba-huang-hou-wen-ti.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
