Solving Search Maze
In this article we will look to solve one of the classic graph problems, searching in a maze.
Problem statement
We will represent the O entries with 0’s and X entries with 1’s. The O entries represent open areas and the X entries represent walls. The entrance and the exit points are represented by an array, the 0th index represents the column and the 1th index represent the row.
Understanding the problem
We can use a DFS approach to recursively traverse the maze.
We first think of our base case, or how we will know when to stop recursing, is either
- We have reached our exit and we’d set our hasPath variable to true
- We have visited every O entry and did not find the exit so we return.
- We are out of bounds so we’d return out of the recurion.
- We are in a visited index so we’d return
Our time complexity for this would be O(v+e).
In order to keep track of the cells we have visited, we will replace the O with 1.
Our recursive action will be to move to all the positions we are able. We will capture this movement by increasing or decreasing either our column or our row. We are able to move:
- up:
col, row + 1
- down:
col, row - 1
- right:
col + 1, row
- left:
col - 1, row
We are not able to move diagonally.
Diagram
Pseudocode
Code
Well that was fun. Let’s see what other graph problem we can solve.