Grokking Graph Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Solution: The Maze
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

There is a ball in a maze with empty spaces (0) and walls (1). The ball can move up, down, left, or right through empty spaces but won't stop until it hits a wall. When the ball stops, it can change direction.

Given an m x n maze, the ball's start position, and the destination, where start = [start<sub>row</sub>, start<sub>col</sub>] and destination = [destination<sub>row</sub>, destination<sub>col</sub>], return true if the ball can stop at the destination. If the ball can't stop at the destination, return false.

Examples

Example 1:

  • Input: start = [0, 4], destination = [0, 1], maze =
     [[0, 0, 1, 0, 0],
      [0, 0, 0, 0, 0],
      [0, 0, 0, 1, 0],
      [1, 1, 0, 1, 1],
      [0, 0, 0, 0, 0]]
    
    
  • Expected Output: true
Image
  • Justification: One possible way to stop at the destination is:- left -> down -> left -> up -> right.

Example 2:

  • Input: start = [0, 3], destination = [4, 4], maze =
   [[0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0],
    [1, 1, 0, 1, 1],
    [0, 0, 0, 0, 0]]

  • Expected Output: true
Image
  • Justification: One possible way to stop at the destination is:- down -> left -> down -> right -> down -> right.

Example 3:

  • Input: start = [0, 3], destination = [1, 1], maze =
     [[0, 0, 1, 0, 0],
      [0, 0, 0, 0, 0],
      [0, 0, 0, 1, 0],
      [1, 1, 0, 1, 1],
      [0, 0, 0, 0, 0]]
    
    
  • Expected Output: false
Image
  • Justification: The ball cannot stop at (1, 1) because it is not hitting the walls.

Constraints:

  • m == maze.length
  • n == maze[i].length
  • 1 <= m, n <= 100
  • maze[i][j] is 0 or 1.
  • start.length == 2
  • destination.length == 2
  • 0 <= start<sub>row</sub>, destination<sub>row</sub> < m
  • 0 <= start<sub>col</sub>, destination<sub>col</sub> < n
  • Both the ball and the destination exist in an empty space, and they will not be in the same position initially.
  • The maze contains at least 2 empty spaces.

Solution

To solve this problem using BFS (Breadth-First Search), we start at the initial position and explore all possible moves in four directions (up, down, left, right). We use a queue to keep track of positions to explore next, and a set to keep track of visited positions to avoid re-processing them. For each move, the ball keeps rolling until it hits a wall. If the ball can stop at the destination, we return true. If the queue is exhausted and the destination is not reached, we return false.

The BFS approach is effective for this problem because it explores all possible paths in a level-order manner, ensuring that the shortest path (if any) to the destination is found. Using a queue helps manage the exploration of positions, while a set of visited positions prevents infinite loops and redundant calculations.

Step-by-Step Algorithm

  1. Initialization:

    • Create a queue and add the starting position [start[0], start[1]] to it.
    • Initialize a 2D array visited of the same size as the maze to keep track of visited positions, and mark the starting position as visited.
    • Define the four possible directions for movement: right, down, left, and up.
  2. BFS Traversal:

    • While the queue is not empty, repeat the following steps:
      • Dequeue the front position from the queue and assign it to curr.
      • If curr is equal to the destination, return true.
      • For each direction in the defined directions, perform the following steps:
        • Initialize x and y with the current position values.
        • Roll the ball in the current direction until it hits a wall or the boundary of the maze.
        • Update x and y with the new position values.
        • If the new position [x, y] is not visited, mark it as visited and enqueue it.
  3. End Condition:

    • If the queue is exhausted and the destination is not reached, return false.

Algorithm Walkthrough

Let's walk through the BFS algorithm with the input:

start = [0, 4]
destination = [0, 1]
maze = [
  [0, 0, 1, 0, 0],
  [0, 0, 0, 0, 0],
  [0, 0, 0, 1, 0],
  [1, 1, 0, 1, 1],
  [0, 0, 0, 0, 0]
]
  1. Initialization:

    • queue = [[0, 4]]
    • directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
  2. First Iteration:

    • curr = [0, 4] (dequeue the front of the queue)
    • Check if curr == destination. It's not.
    • Explore all four directions from [0, 4]:
      • Right (0, 1):
        • Roll the ball to [0, 4] (stays in place, already at the edge of the maze).
      • Down (1, 0):
        • Roll the ball to [2, 4] (stops at the wall at [3, 4]).
        • Mark [2, 4] as visited and enqueue it.
        • queue = [[2, 4]]
      • Left (0, -1):
        • Roll the ball to [0, 3] (stops at the wall at [0, 2]).
        • Mark [0, 3] as visited and enqueue it.
        • queue = [[2, 4], [0, 3]]
      • Up (-1, 0):
        • Roll the ball to [0, 4] (stays in place, already at the edge of the maze).
  3. Second Iteration:

    • curr = [2, 4] (dequeue the front of the queue)
    • Check if curr == destination. It's not.
    • Explore all four directions from [2, 4]:
      • Right (0, 1):
        • Roll the ball to [2, 4] (stays in place, already at the edge of the maze).
      • Down (1, 0):
        • Roll the ball to [2, 4] (stays in place, hits the wall at [3, 4]).
      • Left (0, -1):
        • Roll the ball to [2, 3] (stops at the wall at [2, 3]).
      • Up (-1, 0):
        • Roll the ball to [0, 4] (already visited).
  4. Third Iteration:

    • curr = [0, 3] (dequeue the front of the queue)
    • Check if curr == destination. It's not.
    • Explore all four directions from [0, 3]:
      • Right (0, 1):
        • Roll the ball to [0, 4] (already visited).
      • Down (1, 0):
        • Roll the ball to [1, 3].
        • Mark [1, 3] as visited and enqueue it.
        • queue = [[1, 3]]
      • Left (0, -1):
        • Roll the ball to [0, 2] (stops at the wall at [0, 2]).
      • Up (-1, 0):
        • Roll the ball to [0, 3] (stays in place, already at the edge of the maze).
  5. Fourth Iteration:

    • curr = [1, 3] (dequeue the front of the queue)
    • Check if curr == destination. It's not.
    • Explore all four directions from [1, 3]:
      • Right (0, 1):
        • Roll the ball to [1, 4].
        • Mark [1, 4] as visited and enqueue it.
        • queue = [[1, 4]]
      • Down (1, 0):
        • Roll the ball to [2, 3] (stays in place, hits the wall at [2, 3]).
      • Left (0, -1):
        • Roll the ball to [0, 1].
        • Mark [0, 1] as visited and enqueue it.
        • queue = [[1, 4], [0, 1]]
      • Up (-1, 0):
        • Roll the ball to [0, 3] (already visited).
  6. Fifth Iteration:

    • curr = [1, 4] (dequeue the front of the queue)
    • process it.
  7. Sixth Iteration:

    • curr = [0, 1] (dequeue the front of the queue)
    • Check if curr == destination. It is.
    • Return true.

Thus, the ball can reach the destination [0, 1].

Code

Python3
Python3

. . . .

Complexity Analysis

Time Complexity

The time complexity of the BFS approach for this problem is O(m \cdot n \cdot (m + n)), where (m) is the number of rows and (n) is the number of columns in the maze. This is because in the worst case, we might need to traverse the entire maze in each direction (up, down, left, right) for each cell.

Space Complexity

The space complexity is O(m \cdot n). This is due to the space required for the visited array and the queue used in the BFS. The visited array stores a boolean value for each cell, and the queue stores positions that need to be explored.

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible