Magicsheet logo

Check if There is a Valid Path in a Grid

Medium
87.6%
Updated 6/1/2025

Check if There is a Valid Path in a Grid

What is this problem about?

You are given a grid where each cell contains a "street" type (1-6). Each type represents a specific connection (e.g., Type 1 connects Left and Right, Type 2 connects Top and Bottom). You start at the top-left and want to know if there's a path to the bottom-right. Crucially, two adjacent cells only connect if both streets "point" to each other.

Why is this asked in interviews?

Robinhood and other tech companies ask this to test your ability to handle complex conditional logic within a graph traversal. It’s not just about "can I move there?", but "do the pieces fit together?". It evaluates your skills in BFS, DFS, or Union Find and your ability to model connectivity rules cleanly.

Algorithmic pattern used

The primary pattern is Graph Traversal (BFS or DFS). You treat the grid as a graph where each cell is a node. An edge exists between (r1,c1)(r1, c1) and (r2,c2)(r2, c2) if the street type in the first cell allows movement to the second, AND the street type in the second cell allows movement back to the first. You can pre-map the connection rules for each street type to make the traversal logic cleaner.

Example explanation

Cell (0,0) has Type 1 (Left-Right). Cell (0,1) has Type 1 (Left-Right).

  • (0,0) points Right to (0,1).
  • (0,1) points Left to (0,0). They are connected. If Cell (0,1) had Type 2 (Top-Bottom):
  • (0,0) points Right to (0,1).
  • (0,1) does NOT point Left. They are NOT connected.

Common mistakes candidates make

The most common mistake is forgetting the "mutual connection" rule—checking if you can move from A to B but not checking if B accepts a connection from A. Another error is overcomplicating the connection logic with a massive if-else block instead of using a clean lookup table or direction-based bitmask.

Interview preparation tip

For problems with complex connectivity rules, use a "Direction Map." For example, map Type 1 -> [Left, Right]. This makes your neighbor-checking code much more readable and less prone to logic errors.

Similar Questions