Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Knight Moves Shortest Path

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Knight Moves Shortest Path. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

KLA inspection software models a wafer inspection region as a rectangular grid. Given a horse, the king's location, and blocked cells, return the shortest legal path from the horse to the king using chess horse moves.

A horse move changes the row by exactly 1 and the column by exactly 2, or the row by exactly 2 and the column by exactly 1. The horse may not leave the board or enter a blocked cell. If multiple shortest paths exist, return the one discovered first using this move order: (-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1).

Return the complete path as a list of [row, column] coordinates, including both endpoints. Return an empty list if the king cannot be reached.

Formal Specification

Implement shortest_horse_path(rows, cols, start, king, blocked), where rows and cols are integers, start and king are two-element coordinate lists, and blocked is a list of coordinate lists. Return a list of coordinate lists.

Constraints

  • 1 <= rows, cols <= 2000
  • 0 <= len(blocked) <= 100000
  • All coordinates are within the board
  • start and king are unblocked
  • No coordinate appears more than once in blocked

Function Signature

def shortest_horse_path(rows, cols, start, king, blocked):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output