Skip to content

ORIGINAL CODING QUESTION

Knight hops across a club board

At the campus chess club a knight jumps two squares in one direction and then one square sideways. On a board of rows × cols squares, return the fewest jumps that take the knight from its start square to the target square without leaving the board. Return 0 when start and target coincide and -1 when the target can never be reached.

Open practice workspace

Original exercise · easy. Editorial role relevance does not imply a company has asked this question.

Input and output

rows cols r1 c1 r2 c2: board size, start square and target square (zero-based).

Constraints

1 ≤ rows,cols ≤ 8; both squares lie on the board.

Example 1

Input

8 8 0 0 7 7

Output

6

Corner to opposite corner of a standard board takes six jumps.

Example 2

Input

3 3 0 0 1 1

Output

-1

No knight jump ever lands on the centre of a 3×3 board.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Each square is a vertex and each legal jump is an unweighted edge.

Hint 2

Breadth-first search finds the fewest jumps.

Hint 3

Generate the eight jump offsets and skip ones that leave the board.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →