Rat in a Maze

Recursion FAQs (Hard) Hard
  • This problem statement is a practical manifestation of pathfinding algorithms used in a variety of disciplines in software development
  • A prime example can be found in video game development, where these algorithms allow characters to navigate around obstacles in an environment
  • In particular, the A* (A-star) search algorithm, which incorporates heuristic information, is commonly used for its efficiency and accuracy in finding the shortest path
  • Additionally, similar problem-solving structures are used in web routing protocols and Global Positioning System (GPS) for finding the shortest route between two locations

Given a grid of dimensions n x n. A rat is placed at coordinates (0, 0) and wants to reach at coordinates (n-1, n-1).Find all possible paths that rat can take to travel from (0, 0) to (n-1, n-1). The directions in which rat can move are 'U' (up) , 'D' (down) , 'L' (left) , 'R' (right).


The value 0 in grid denotes that the cell is blocked and rat cannot use that cell for travelling, whereas value 1 represents that rat can travel through the cell. If the cell (0, 0) has 0 value, then mouse cannot move to any other cell.

Examples:

Input : n = 4 , grid = [ [1, 0, 0, 0] , [1, 1, 0, 1], [1, 1, 0, 0], [0, 1, 1, 1] ]

Output : [ "DDRDRR" , "DRDDRR" ]

Explanation : The rat has two different path to reach (3, 3).

The first path is (0, 0) => (1, 0) => (2, 0) => (2, 1) => (3, 1) => (3, 2) => (3, 3).

The second path is (0,0) => (1,0) => (1,1) => (2,1) => (3,1) => (3,2) => (3,3).

Input : n = 2 , grid = [ [1, 0] , [1, 0] ]

Output : -1

Explanation : There is no path that rat can choose to travel from (0,0) to (1,1).

Input : n = 3 , grid = [ [1, 0, 0] , [1, 1, 0], [0, 1, 1] ]

Constraints

  • 2 <= n <= 5
  • 0 <= grid[i][j] <= 1

Hints

  • Use recursion to explore all possible moves from the current cell. At each step, check if the current cell is valid for traversal (inside the grid, unvisited, and not blocked). If valid, mark the cell as visited and attempt to move in all four possible directions. Append the direction (U, D, L, R) to the current path while moving.
  • If the current cell is (n−1,n−1), it means the rat has reached the destination. Add the current path to the list of results. If the current cell is invalid (out of bounds, blocked, or already visited), return immediately without proceeding further.

Company Tags

Boston Consulting Group Snowflake Unity Technologies Ubisoft OYO Rooms Broadcom Cloudflare MongoDB Chewy Teladoc Health Swiggy Splunk Walmart Johnson & Johnson Oracle Reddit Square Target Nutanix McKinsey & Company AMD Twilio ARM PwC Docker Google Microsoft Amazon Meta Apple Netflix Adobe