Teaching Kids Programming – Nearest Exit from Entrance in Maze via Breadth First Search Algorithm (BFS)


Teaching Kids Programming: Videos on Data Structures and Algorithms

You are given an m x n matrix maze (0-indexed) with empty cells (represented as ‘.’) and walls (represented as ‘+’). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.

In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.

find-the-nearest-exit-in-the-maze Teaching Kids Programming - Nearest Exit from Entrance in Maze via Breadth First Search Algorithm (BFS) algorithms Breadth First Search Graph Algorithm python teaching kids programming youtube video

find-the-nearest-exit-in-the-maze

Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.

Example 1:
Input: maze = [[“+”,”+”,”.”,”+”],[“.”,”.”,”.”,”+”],[“+”,”+”,”+”,”.”]], entrance = [1,2]
Output: 1
Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].
Initially, you are at the entrance cell [1,2].
– You can reach [1,0] by moving 2 steps left.
– You can reach [0,2] by moving 1 step up.
It is impossible to reach [2,3] from the entrance.
Thus, the nearest exit is [0,2], which is 1 step away.

Example 2:
Input: maze = [[“+”,”+”,”+”],[“.”,”.”,”.”],[“+”,”+”,”+”]], entrance = [1,0]
Output: 2
Explanation: There is 1 exit in this maze at [1,2].
[1,0] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell [1,0].
– You can reach [1,2] by moving 2 steps right.
Thus, the nearest exit is [1,2], which is 2 steps away.

Example 3:
Input: maze = [[“.”,”+”]], entrance = [0,0]
Output: -1
Explanation: There are no exits in this maze.

Constraints:
maze.length == m
maze[i].length == n
1 <= m, n <= 100
maze[i][j] is either ‘.’ or ‘+’.
entrance.length == 2
0 <= entrancerow < m
0 <= entrancecol < n
entrance will always be an empty cell.

Hints:
Which type of traversal lets you find the distance from a point?
Try using a Breadth First Search.

Nearest Exit from Entrance in Maze via Breadth First Search Algorithm

Path finding in a maze is to find the shortest path(s) in a undirected unweighted graph. Each empty cell in the maze has four directions to check: up, down, left and right. We can do a Breadth First Search Algorithm (BFS) which is suitable in finding the shortest path if any in a unweighted Graph. We can start searching from the entry and terminate at any exit (which is an empty cell on the border and not the given entry).

When next moves (together with cells in the tuples) are pushed to the queue, we increment the steps (distance) by one. We also need to avoid re-visiting the same cells, which can be done via a hash set.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: 
        rows = len(maze)
        assert rows > 0
        cols = len(maze[0])
        assert cols > 0
 
        def isExit(r, c):
            if r == 0 or c == 0 or r == rows - 1 or c == cols - 1:
                return maze[r][c] == '.'
            return False
 
        seen = set()
        q = deque([(entrance, 0)])
 
        while q:
            (r, c), d = q.popleft()
            if (r, c) != tuple(entrance) and isExit(r, c):
                return d
            for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                nr, nc = dr + r, dc + c
                if (nr, nc) in seen or nr < 0 or nc < 0 or nr == rows or nc == cols:
                    continue
                if maze[nr][nc] == '.':
                    seen.add((nr, nc))
                    q.append(((nr, nc), d + 1))
        return -1
class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: 
        rows = len(maze)
        assert rows > 0
        cols = len(maze[0])
        assert cols > 0

        def isExit(r, c):
            if r == 0 or c == 0 or r == rows - 1 or c == cols - 1:
                return maze[r][c] == '.'
            return False

        seen = set()
        q = deque([(entrance, 0)])

        while q:
            (r, c), d = q.popleft()
            if (r, c) != tuple(entrance) and isExit(r, c):
                return d
            for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                nr, nc = dr + r, dc + c
                if (nr, nc) in seen or nr < 0 or nc < 0 or nr == rows or nc == cols:
                    continue
                if maze[nr][nc] == '.':
                    seen.add((nr, nc))
                    q.append(((nr, nc), d + 1))
        return -1

Alternatively, we can mark the visited cells walls – however, this requires checking if the next cells are the exits when we push them to the queue rather than when we deque them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: 
        rows = len(maze)
        assert rows > 0
        cols = len(maze[0])
        assert cols > 0
 
        def isExit(r, c):
            if r == 0 or c == 0 or r == rows - 1 or c == cols - 1:
                return maze[r][c] == '.'
            return False
 
        q = deque([(entrance, 0)])
 
        while q:
            (r, c), d = q.popleft()
            for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                nr, nc = dr + r, dc + c
                if nr < 0 or nc < 0 or nr == rows or nc == cols:
                    continue
                if maze[nr][nc] == '.':
                    q.append(((nr, nc), d + 1))
                    if (nr, nc) != tuple(entrance) and isExit(nr, nc):
                        return d + 1                   
                    # set it to wall
                    maze[nr][nc] = '+'
        return -1
class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: 
        rows = len(maze)
        assert rows > 0
        cols = len(maze[0])
        assert cols > 0

        def isExit(r, c):
            if r == 0 or c == 0 or r == rows - 1 or c == cols - 1:
                return maze[r][c] == '.'
            return False

        q = deque([(entrance, 0)])

        while q:
            (r, c), d = q.popleft()
            for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                nr, nc = dr + r, dc + c
                if nr < 0 or nc < 0 or nr == rows or nc == cols:
                    continue
                if maze[nr][nc] == '.':
                    q.append(((nr, nc), d + 1))
                    if (nr, nc) != tuple(entrance) and isExit(nr, nc):
                        return d + 1                   
                    # set it to wall
                    maze[nr][nc] = '+'
        return -1

We can push all the exits to the queue and start a Breadth First Search which terminates when we find the entry.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: 
        rows = len(maze)
        assert rows > 0
        cols = len(maze[0])
        assert cols > 0
 
        def isExit(r, c):
            if r == 0 or c == 0 or r == rows - 1 or c == cols - 1:
                return maze[r][c] == '.'
            return False
 
        seen = set()
        q = deque()
        for r in range(rows):
            for c in range(cols):
                if (r, c) != tuple(entrance) and isExit(r, c):
                    q.append(((r, c), 0))
 
        while q:
            (r, c), d = q.popleft()
            if (r, c) == tuple(entrance):
                return d
            for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                nr, nc = dr + r, dc + c
                if (nr, nc) in seen or nr < 0 or nc < 0 or nr == rows or nc == cols:
                    continue
                if maze[nr][nc] == '.':
                    seen.add((nr, nc))
                    q.append(((nr, nc), d + 1))
        return -1
class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: 
        rows = len(maze)
        assert rows > 0
        cols = len(maze[0])
        assert cols > 0

        def isExit(r, c):
            if r == 0 or c == 0 or r == rows - 1 or c == cols - 1:
                return maze[r][c] == '.'
            return False

        seen = set()
        q = deque()
        for r in range(rows):
            for c in range(cols):
                if (r, c) != tuple(entrance) and isExit(r, c):
                    q.append(((r, c), 0))

        while q:
            (r, c), d = q.popleft()
            if (r, c) == tuple(entrance):
                return d
            for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                nr, nc = dr + r, dc + c
                if (nr, nc) in seen or nr < 0 or nc < 0 or nr == rows or nc == cols:
                    continue
                if maze[nr][nc] == '.':
                    seen.add((nr, nc))
                    q.append(((nr, nc), d + 1))
        return -1

The time/space complexity is O(N) where N is the number of cells in the maze.

Nearest Exit from Entrance in Maze

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
1244 words
Last Post: Teaching Kids Programming - Minimum Sum of Four Digit Number After Splitting Digits
Next Post: Teaching Kids Programming - Minimum Cuts to Divide a Circle

The Permanent URL is: Teaching Kids Programming – Nearest Exit from Entrance in Maze via Breadth First Search Algorithm (BFS)

Leave a Reply