ProgrammingVery hardCodeforces-style · placement coding round

What is printed?

What is printed?
from collections import deque
def knight(src, dst):
    seen = {src: 0}
    q = deque([src])
    moves = [(1, 2), (2, 1), (-1, 2), (-2, 1), (1, -2), (2, -1), (-1, -2), (-2, -1)]
    while q:
        r, c = q.popleft()
        if (r, c) == dst:
            return seen[(r, c)]
        for dr, dc in moves:
            nr, nc = r + dr, c + dc
            if 0 <= nr < 8 and 0 <= nc < 8 and (nr, nc) not in seen:
                seen[(nr, nc)] = seen[(r, c)] + 1
                q.append((nr, nc))
print(knight((0, 0), (2, 1)), knight((0, 0), (7, 7)))
  1. A. 2 6
  2. B. 1 6
  3. C. 1 7
  4. D. 2 7

Correct answer: B. 1 6

Breadth-first search over the eight knight moves gives the minimum number of moves. One move reaches (2, 1), and six moves are needed to reach the opposite corner (7, 7).

More Python Programming questions

Exams that ask this topic