KatInterview

Minimum Hops Between Nodes in a Matrix-Represented Graph

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsgraphsbfsadjacency-matrix

Last updated

Tests ability to implement BFS on an undirected unweighted graph stored as an adjacency matrix to find the fewest edges between two nodes.

Minimum Hops Between Two Nodes

You have an undirected, unweighted graph of n nodes numbered 0 through n - 1. The graph is described by an n x n binary matrix called conn, where conn[i][j] == 1 means there is a direct edge between node i and node j, and conn[i][j] == 0 means there is no such edge.

Given a starting node start and a target node end, return the fewest number of edges that must be traversed to travel from start to end.

  • If start and end are the same node, the answer is 0.
  • If no path connects start to end, return -1.

Input

  • conn: A 2D list of integers with dimensions n x n. Every entry is either 0 or 1. The matrix is symmetric (conn[i][j] == conn[j][i]) and has no self-loops (conn[i][i] == 0).
  • start: An integer index of the source node (0 <= start < n).
  • end: An integer index of the destination node (0 <= end < n).

Output

An integer: the minimum number of edges on any path from start to end, or -1 if the two nodes belong to different connected components.

Constraints

  • 1 <= n <= 1000
  • 0 <= start, end < n
  • conn[i][i] == 0 for all 0 <= i < n
  • conn[i][j] == conn[j][i] for all 0 <= i, j < n
  • Each entry conn[i][j] is 0 or 1

Examples

Example 1

Input: min_hops([[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]], 0, 3)

Output: 2

Example 2

Input: min_hops([[0, 1, 0], [1, 0, 0], [0, 0, 0]], 0, 2)

Output: -1

Example 3

Input: min_hops([[0, 1], [1, 0]], 1, 1)

Output: 0

Hints

Hint 1

The graph is unweighted, so the shortest path by edge count is the one BFS reaches first — not DFS, and not Dijkstra. Think about what BFS explores at each 'layer'.

Hint 2

When you dequeue a node, scan its entire row in `conn` to find neighbors. Mark a neighbor as visited the moment you add it to the queue, not when you pop it, to avoid adding the same node multiple times.

Hint 3

Handle `start == end` before the BFS loop starts — the loop only checks newly discovered neighbors, so it would miss this case and return the wrong answer.