Skip to content

Latest commit

 

History

History
 
 

3001

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

There is a 1-indexed 8 x 8 chessboard containing 3 pieces.

You are given 6 integers a, b, c, d, e, and f where:

  • (a, b) denotes the position of the white rook.
  • (c, d) denotes the position of the white bishop.
  • (e, f) denotes the position of the black queen.

Given that you can only move the white pieces, return the minimum number of moves required to capture the black queen.

Note that:

  • Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces.
  • Bishops can move any number of squares diagonally, but cannot jump over other pieces.
  • A rook or a bishop can capture the queen if it is located in a square that they can move to.
  • The queen does not move.

 

Example 1:

Input: a = 1, b = 1, c = 8, d = 8, e = 2, f = 3
Output: 2
Explanation: We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3).
It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning.

Example 2:

Input: a = 5, b = 3, c = 3, d = 4, e = 5, f = 2
Output: 1
Explanation: We can capture the black queen in a single move by doing one of the following: 
- Move the white rook to (5, 2).
- Move the white bishop to (5, 2).

 

Constraints:

  • 1 <= a, b, c, d, e, f <= 8
  • No two pieces are on the same square.

Companies: Goldman Sachs

Related Topics:
Array, Enumeration

Similar Questions:

Hints:

  • The minimum number of moves can be either 1 or 2.
  • The answer will be 1 if the queen is on the path of the rook or bishop and none of them is in between.

Solution 1.

// OJ: https://leetcode.com/problems/minimum-moves-to-capture-the-queen
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
    int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) {
        if (a == e) {
            if (a != c || (d - b) * (f - b) < 0 || abs(d - b) > abs(f - b)) return 1;
        }
        if (b == f) {
            if (b != d || (c - a) * (e - a) < 0 || abs(c - a) > abs(e - a)) return 1;
        }
        int ac = a - c, ec = e - c, bd = b - d, fd = f - d;
        if (abs(ec) == abs(fd)) {
            if (abs(ac) != abs(bd)) return 1;
            if (ac / abs(ac) != ec / abs(ec) || bd / abs(bd) != fd / abs(fd)) return 1;
            if (abs(ec) < abs(ac)) return 1;
        }
        return 2;
    }
};