[] _10_ data structures and algorithms pruning

[A] Interview (interview questions)

 

[1.1] LeetCode 51 is 52 is: N Queens (Queens N)

Description Title : Drafts, n queens how nxn placed on the board, and can not attack each other such that between Queen

  • The DFS (depth-first search)
result = []

# 深度优先遍历
def DFS(cols, na, pie, n):
    '''
    :param cols: 列表,存储皇后所在的列的索引
    :param na: 列表,存储皇后辐射的反斜区域
    :param pie: 列表,存储皇后辐射的正斜区域
    :param n: 数字,表示有几个皇后
    '''
    p = len(cols)
    if p == n:
        result.append(cols)
        return None
    for q in range(n):
        if q not in cols and p-q not in na and p+q not in pie:
            DFS(cols+[q], na+[p-q], pie+[p+q], n)

# 调用函数并返回结果
def solveNQueen(n):
    DFS([], [], [], n)
    return [ ['.'*i + 'Q' + '.'*(n-i-1) for i in sol] for sol in result ]

print(solveNQueen(4))
Published 54 original articles · won praise 5 · Views 2627

Guess you like

Origin blog.csdn.net/qq_34330456/article/details/104681704