MediumProgramming
How can Python check whether a rook can move between two squares in one move?
TL;DR
A rook can do so if the squares share a file or rank:
x1 == x2 or y1 == y2.Question
Given two distinct chessboard squares, determine whether a rook can move from the first to the second in one move. Ignore obstructions by other pieces.
Input
Four integers from 1 to 8: the file and rank of the first square, followed by those of the second. The numbers may be on separate lines.
Output
Print YES if the move is possible; otherwise print NO.
Examples
| Input numbers | Output |
|---|---|
| 6 6 8 8 | NO |
| 1 4 7 4 | YES |
| 2 6 2 1 | YES |
Explanation
A rook moves vertically or horizontally. Check whether the file coordinates or rank coordinates are equal. The statement guarantees that the squares are distinct.
import sys
x1, y1, x2, y2 = map(int, sys.stdin.read().split())
print('YES' if x1 == x2 or y1 == y2 else 'NO')
sys.stdin.read().split() handles both spaces and line breaks. For the fixed four coordinates, the program uses O(1) time and additional memory.
Platforms
- MAXIMUM
