采访准备:K女王攻击

时间:2017-02-02 06:28:12

标签: algorithm grid-layout

我有一个N乘N网格和K皇后。 女王可以垂直,水平或对角移动。我想知道是否任何女王在O(N)时间内可以攻击任何其他女王。

2 个答案:

答案 0 :(得分:1)

使用与the last answer for rook problem中相同的技术,只需为对角线添加数组。 DiagUpRight[2*N-1]DiagUpLeft[2*N-1]

Q(x,y)标记对角线DiagUpLeft[x + y]DiagUpRight[N-1 - y + x]

答案 1 :(得分:0)

q_rowq_col表示女王q的行和列。然后你可以用这个伪代码解决你的问题:

for each q in Queens do
    if row[q_row] or column[q_col] or 
       diag1[N + q_row - q_col] or diag2[q_row + q_col] then
        output 'Attacking queen found.'
        break
    else
        row[q_row] = true
        column[q_col] = true
        diag1[N + q_row - q_col] = true
        diag2[q_row + q_col] = true