Problem 592439 · medium · Phase 05 Advanced Algorithms & Graphs

Knight Hops on a Fenced Board

grids · BFS · implicit graph

A knight stands on an n x n board with rows and columns numbered 0 .. n-1. In one hop it moves two squares in one direction and one square in a perpendicular direction (eight possible offsets) and must land on the board. Return the minimum number of hops from start = [r0, c0] to target = [r1, c1], or -1 if the target cannot be reached.

Examples

Input:  n = 8, start = [0,0], target = [1,2]
Output: 1

Input:  n = 3, start = [0,0], target = [1,1]
Output: -1
Explanation: on a 3x3 board no hop ever lands on the centre square.

Input:  n = 8, start = [3,3], target = [3,3]
Output: 0

Constraints

  • 1 <= n <= 120
  • Target O(n^2) time.

Goals

  • Treat board squares as graph nodes and knight moves as edges
  • Run BFS over an implicit graph without building an adjacency list
Starting Python…