Shortest Path for a Hobbled Xiangqi Horse on a 10×9 Board
Trees & GraphsModel answerLast updated
Find the minimum moves for a Chinese-chess horse to reach a target on a 10×9 grid, accounting for the leg-blocking movement restriction and obstacle squares.
Background
In Xiangqi (Chinese chess), the horse moves in a shape similar to a Western knight's "L", but with an extra constraint known as "hobbling the leg" (蹩马腿). Before the horse can complete its jump, it must pass through an intermediate square called the leg. If that leg square is occupied by an obstacle, the entire move in that direction is forbidden.
Movement Rules
From square (r, c), the horse has up to four possible leg directions, each unlocking two jump destinations:
| Leg square | Reachable destinations |
|---|---|
(r-1, c) — up leg | (r-2, c-1) and (r-2, c+1) |
(r+1, c) — down leg | (r+2, c-1) and (r+2, c+1) |
(r, c-1) — left leg | (r-1, c-2) and (r+1, c-2) |
(r, c+1) — right leg | (r-1, c+2) and (r+1, c+2) |
A move to a destination is only legal when all three of these hold:
- The leg square is within the board and is not an obstacle.
- The destination square is within the board.
- The destination square is not an obstacle.
Task
Given a 10 × 9 board as a 2-D integer array (0 = empty, 1 = obstacle), a start position, and a target position, return the minimum number of moves for the horse to travel from start to target. Return -1 if no legal path exists.
Function Signature
def min_horse_moves(
board: list[list[int]],
start: tuple[int, int],
target: tuple[int, int]
) -> int:
pass
Constraints
len(board) == 10,len(board[0]) == 9board[r][c] ∈ {0, 1}0 <= start[0], target[0] < 100 <= start[1], target[1] < 9- If
board[start[0]][start[1]] == 1orboard[target[0]][target[1]] == 1, return-1. - If
start == targetand that square is empty, return0.
Examples
Example 1 — clear board, one move
board : 10×9 grid of all zeros
start : (0, 0)
target : (2, 1)
output : 1
The up-leg (1, 0) is empty, so the horse jumps directly to (2, 1).
Example 2 — blocked leg, longer detour
board : 10×9 grid of all zeros except board[1][0] = 1
start : (0, 0)
target : (2, 1)
output : 3
The direct jump is forbidden because the leg (1, 0) is blocked.
One valid 3-move path: (0,0) → (1,2) → (3,3) → (2,1).
Hints
Hint 1
Think of every empty board square as a node. Two nodes are connected when the horse can legally jump between them under the leg rule. What algorithm finds shortest paths on an unweighted graph?
Hint 2
Organize your move generator around the four legs, not the eight destinations. For each leg, first check whether that square is clear before you even look at its two destinations. This makes the hobbling rule almost impossible to implement incorrectly.
Hint 3
Mark a square as visited the moment you add it to the queue, not when you pop it. This prevents the same square from being enqueued multiple times at the same depth, which would silently inflate your move count.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every empty square is a node in an unweighted directed graph. An edge A → B exists when the horse can legally jump from A to B. Because every edge has cost 1, BFS from start yields the minimum number of moves. The only problem-specific work is writing a correct move generator that respects the leg-blocking rule.
Move Generator Design
Group the eight possible destinations under their four parent legs. For each leg:
- If the leg square is off the board or contains an obstacle, skip both of its destinations — the move is forbidden regardless of where the horse would land.
- Otherwise, check each destination independently: it must be inside the board and obstacle-free.
This structure is cleaner than iterating over destinations and backtracking to find which leg each one requires.
Leg offset → Destination offsets
(-1, 0) → [(-2, -1), (-2, +1)] # up
(+1, 0) → [(+2, -1), (+2, +1)] # down
( 0, -1) → [(-1, -2), (+1, -2)] # left
( 0, +1) → [(-1, +2), (+1, +2)] # right
Why BFS Is Correct
BFS visits nodes in non-decreasing order of distance from the source. The first time the target is discovered, its depth equals the shortest path length — no relaxation or priority queue needed. Marking nodes visited on enqueue (not on dequeue) ensures each node enters the queue at most once, keeping time complexity linear.
The graph is directed: the move A → B uses a leg adjacent to A, while B → A uses a different leg adjacent to B. One direction can be blocked while the other is open, so a standard directed BFS handles this correctly.
Edge Cases to Handle First
- Obstacle on start or target → return
-1before doing anything else. start == targeton an empty square → return0.- Leg off the board acts as a blocker (a horse in row 0 cannot step to row -1).
- One destination blocked, sibling valid → only skip the blocked destination; the sibling on the same leg may still be reachable.
- Target completely surrounded by blocked legs → BFS exhausts the queue and returns
-1.
Worked Example 2 Trace
board[1][0] = 1, start (0,0), target (2,1).
- Move via up-leg
(1,0)is blocked (obstacle). - Move
(0,0) → (1,2)uses right-leg(0,1)— clear. ✓ (depth 1) - Move
(1,2) → (3,3)uses down-leg(2,2)— clear. ✓ (depth 2) - Move
(3,3) → (2,1)uses left-leg(3,2)— clear. ✓ (depth 3)
Answer: 3. A parity check confirms no 1-move path exists (the direct route is blocked) and no 2-move path can work because (r+c) changes by an odd amount each move — going from parity 0 to parity 3 requires an odd number of moves, so 3 is optimal.
Implementation
from collections import deque
def min_horse_moves(
board: list[list[int]],
start: tuple[int, int],
target: tuple[int, int]
) -> int:
rows, cols = len(board), len(board[0])
sr, sc = start
tr, tc = target
# Blocked endpoints make the task impossible.
if board[sr][sc] == 1 or board[tr][tc] == 1:
return -1
if start == target:
return 0
# Each entry: (leg_offset, (dest_offset_1, dest_offset_2))
MOVES = (
((-1, 0), ((-2, -1), (-2, 1))), # up
(( 1, 0), (( 2, -1), ( 2, 1))), # down
(( 0, -1), ((-1, -2), ( 1, -2))), # left
(( 0, 1), ((-1, 2), ( 1, 2))), # right
)
def in_bounds_and_free(r: int, c: int) -> bool:
return 0 <= r < rows and 0 <= c < cols and board[r][c] == 0
visited = [[False] * cols for _ in range(rows)]
visited[sr][sc] = True
queue = deque([(sr, sc, 0)])
while queue:
r, c, depth = queue.popleft()
for (lr, lc), destinations in MOVES:
# Leg must be clear before any destination is reachable.
if not in_bounds_and_free(r + lr, c + lc):
continue
for dr, dc in destinations:
nr, nc = r + dr, c + dc
if not in_bounds_and_free(nr, nc) or visited[nr][nc]:
continue
if nr == tr and nc == tc:
return depth + 1 # earliest possible discovery
visited[nr][nc] = True
queue.append((nr, nc, depth + 1))
return -1
Complexity
- Time: O(R × C) — each of the 90 squares is enqueued at most once; each dequeue does O(1) work (4 legs, 8 destinations).
- Space: O(R × C) — for the visited grid and the BFS queue.
Common Mistakes
- Checking the leg against the destination's row/column instead of the horse's current row/column. The leg is always one orthogonal step from where the horse currently stands, not from where it's going.
- Marking visited on dequeue rather than on enqueue. This allows the same square to be enqueued multiple times, wasting work and risking incorrect depth on large boards.
- Forgetting that the graph is directed. Running a single BFS from the target with forward edges (instead of reverse edges) and comparing distances gives wrong answers when one direction is blocked.
- Treating a blocked start that equals the target as 0. The obstacle check must come before the
start == targetcheck.
Follow-up Angles
Recovering the actual path: store parent[nr][nc] = (r, c) when a square is first enqueued, then walk back from target to start after BFS completes.
Scaling to large boards (e.g. 1000 × 1000): plain BFS stays O(N) and handles ~10⁶ nodes fine. For many queries on a fixed board, run BFS once from the target using reverse edges and answer every query in O(1).
Bidirectional BFS: expand from both start and target simultaneously. The backward expansion must use reverse edges — for B → A to be a valid reverse edge, the forward move A → B must be legal, meaning the leg check is performed relative to A, not B.
Time-varying obstacles (periodic with period k): extend the state to (r, c, t mod k), giving k × N states total. BFS still finds the minimum moves; visited becomes a 3-D array.