The question is minimum moves of a knight from point A to B in an n*n chessboard(knights can move two steps in the horizontal direction and one step in the vertical direction or two in vertical one in horizontal). There is a bishop on the chess board that travels diagonally and the knight cannot travel to positions threatened by the bishop unless the bishop is dead or the position is point B. The knight can choose to kill the bishop (if it is in a position that it can travel to) and free all the previously threatened positions.
I got this question in an online assessment that I took, but only got 10 out of 15 test cases correct. I figured I might need to add a boolean value to the tuples in the queue of whether the bishop is alive in the latest step but it was too late.
How can I modify this?
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