Talentd
FleetCode

4034. Minimum Bishop Moves to Reach Target

Medium65.4% acceptance

There is an 8 x 8 empty chessboard with 1-indexed rows and columns.

You are given an array source = [sr, sc] representing the starting position of a bishop, and an array target = [tr, tc]. In one move, the bishop travels any number of squares along a single diagonal direction, staying within the board.

Return the minimum number of moves for the bishop to land exactly on target. If it can never reach target, return -1.

Example 1:

Input: source = [8,1], target = [1,8]

Output: 1

Explanation:

​​​​​​​

A single diagonal move takes the bishop straight from (8, 1) to (1, 8).

Example 2:

Input: source = [4,2], target = [1,3]

Output: 2

Explanation:

The bishop moves from (4, 2) to (3, 1), then from (3, 1) to (1, 3), reaching the target in 2 moves.

Example 3:

Input: source = [1,1], target = [3,4]

Output: -1

Explanation:

No matter how many diagonal moves it makes, the bishop starting at (1, 1) can never land on (3, 4). Thus, the answer is -1.

Constraints:​​​​​​​

  • source.length == target.length == 2
  • 1 <= sr, sc, tr, tc <= 8
  • source != target

Topics

Hints open one at a time

Hint 1
First consider the cases where no move is needed or where the target is unreachable. A bishop always remains on squares of the same color.
Hint 2
Two squares are on the same diagonal if either r - c or r + c is equal for both squares. If the target is reachable but not on the same diagonal, determine how many moves are sufficient.
14:49
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def minBishopMoves(self, source: list[int], target: list[int]) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[8,1]
[1,8]
Input
[4,2]
[1,3]
Input
[1,1]
[3,4]
Your code is saved on this device.Solution