【发布时间】:2021-10-29 22:19:11
【问题描述】:
问题是一个骑士在 n*n 棋盘中从 A 点到 B 点的最小移动(骑士可以在水平方向移动两步,在垂直方向移动一步,或者在水平方向垂直移动两步)。棋盘上有一个主教沿对角线移动,除非主教死了或位置在 B 点,否则马不能移动到主教威胁的位置。马可以选择杀死主教(如果它处于它可以移动到)并释放所有先前受到威胁的位置。
我在参加的在线评估中得到了这个问题,但在 15 个测试用例中只有 10 个正确。我想我可能需要在队列中的元组中添加一个布尔值,以判断主教是否在最近的步骤中还活着,但为时已晚。
如何修改?
from collections import deque
import math
n = 5
startRow = 0
startCol = 0
endRow = 4
endCol = 3
bishopRow = 3
bishopCol = 0
from collections import deque
import math
#
# Complete the 'moves' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER startRow
# 3. INTEGER startCol
# 4. INTEGER endRow
# 5. INTEGER endCol
# 6. INTEGER bishopRow
# 7. INTEGER bishopCol
#
def isBishopAlive(n, bishopRow, bishopCol):
if bishopRow < n and bishopCol < n:
return True
else:
return False
def moves(n, startRow, startCol, endRow, endCol, bishopRow, bishopCol):
# Write your code here
x, y = abs(endRow), abs(endCol)
res = 0
moves = ((2,1), (1,2), (-1,2), (-2,1), (-2,-1), (-1,-2), (1,-2), (2,-1))
visited = []
queue = deque()
queue.append((startRow, startCol, 0))
while queue:
i, j, steps = queue.popleft()
if i == x and j == y:
return res + steps
for di, dj in moves:
cr = i + di
cc = j + dj
if isBishopAlive(n, bishopRow, bishopCol) == True:
if abs(cr-bishopRow) == abs(cc-bishopCol):
if cc != y and cr != x:
continue
if (cr == bishopRow) and (cc == bishopCol):
bishopRow, bishopCol = math.inf, math.inf
if abs(cr) > n-1 or abs(cc) > n-1:
continue
if (cr, cc) in visited:
continue
if isBishopAlive(n, bishopRow, bishopCol) == True:
bishop = True
else:
bishop = False
if ((x-i) * di) > 0 or ((y-j) * dj) > 0:
queue.append([cr, cc, steps+1])
visited.append((cr, cc))
return -1
【问题讨论】:
-
我对你的行
i, j, steps, bishop = current....感到困惑。为什么将相同的值分配给j和steps。你不需要在你的州也包括is_bishop_alive吗? -
很抱歉这是一个错字。我试图在元组中添加主教的状态,但它一直给我错误,说我缺少参数。我编辑了帖子 - 请查看我的原始代码
-
当骑士俘虏主教时,您不能只更改
bishopRow和bishopCol。这意味着在那之后你看到的每一个州,即使是那些主教没有死的州,你都会表现得好像主教已经死了。主教是否被俘虏必须是您保存状态的一部分,就像骑士的位置一样。
标签: python queue depth-first-search