Problem · Graph

Knight Minimum Moves with a Fixed Bishop

Learn this problem
MediumIMC logoIMCINTERNNEW GRADOA

Problem statement

You are given an n-by-n chessboard whose rows and columns are numbered from 0 to n - 1. A knight starts at (startRow, startCol) and must reach (endRow, endCol).

A bishop remains fixed at (bishopRow, bishopCol). The knight may not occupy the bishop's square or any square the bishop attacks. Because the board contains no other pieces, the bishop attacks every in-bounds square on either diagonal through its position.

On each move, the knight changes its row by 2 and its column by 1, or its row by 1 and its column by 2, with either sign. Return the minimum number of legal knight moves needed to reach the target. Return -1 if the start or target is unsafe, or if the target cannot be reached.

Function

minKnightMoves(n: int, startRow: int, startCol: int, endRow: int, endCol: int, bishopRow: int, bishopCol: int) → int

Examples

Example 1

n = 9startRow = 4startCol = 4endRow = 4endCol = 8bishopRow = 0bishopCol = 1return = 2

The target is reachable in two legal knight moves, and neither visited square lies on a bishop diagonal.

Example 2

n = 5startRow = 0startCol = 0endRow = 4endCol = 3bishopRow = 2bishopCol = 2return = -1

The starting square lies on the bishop's diagonal, so no legal route exists.

Constraints

  • 4 <= n <= 150
  • 0 <= startRow, startCol, endRow, endCol, bishopRow, bishopCol < n
  • The bishop remains fixed for the entire route.
  • The knight may not occupy the bishop's square or any square on either bishop diagonal.

More IMC problems

drafts saved locally
class Solution {
    public int minKnightMoves(int n, int startRow, int startCol,
                              int endRow, int endCol,
                              int bishopRow, int bishopCol) {
        // Write your code here.
        return -1;
    }
}
n9
startRow4
startCol4
endRow4
endCol8
bishopRow0
bishopCol1
expected2
checking account