解题思路:
DFS


注意事项:
    代码改进:

        1.dfs内的赋值部分分开写可以缩短运行时间;

        2.这里判断王的坐标的方法比较笨,浪费了很多空间。

参考代码:

def dfs(row=0):
    global r, col_not_occupied, d_1, d_2, cnt
    cnt += 1 if row == r else 0

    for col in range(r):
        if col_not_occupied[col] and d_1[row - col] and d_2[row + col] and \
                map_[row][col]:
                    col_not_occupied[col], d_1[row - col], d_2[row + col] = [False for _ in range(3)]
                    dfs(row + 1)
                    col_not_occupied[col], d_1[row - col], d_2[row + col] = [True for _ in range(3)]


r, x, y = map(int, input().split())
cnt = 0
map_ = [[1 for _ in range(r)] for _ in range(r)]
col_not_occupied = [True for _ in range(r)]
d_1, d_2 = [[True for _ in range(2 * r - 1)] for _ in range(2)]
direction = [[0, 0], [1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, -1], [1, -1], [-1, 1]]
for d in direction:
    if 0 <= x + d[0] - 1 < r and 0 <= y + d[1] - 1 < r:
        map_[x + d[0] - 1][y + d[1] - 1] = 0
dfs()
print(cnt)


 

0.0分

1 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区