Problem 283. Give the Shortest Path Through The Maze
Description
The purpose of this problem is to give the shortest path through a maze. The maze will be provided in a codified matrix of size M x N where each element of the matrix represents a place in the grid and the value of each element is a binary-code that represents the presence of walls. That is:
+ + value = 0 -> 00 -> no walls -> NW + +
+ + value = 1 -> 01 -> wall to W -> | NW + +
+---+ value = 2 -> 10 -> wall to N -> NW + +
+---+ value = 3 -> 11 -> walls to N and W -> | + +
Note: all outer boundaries are walls. My test cases provide for this already. You do not need to account for this.
The path will always start at the NorthWest corner (subscript (1,1)) and end at the SouthEast corner (subscript (M,N)). The output should be a matrix of the same size as the input matrix that lists the steps you need to go through to traverse the maze with the remaining squares being 0. For example,
path = [ 1 2 0 0 0 0 4 3 0 9 10 0 5 6 7 8 11 0 0 0 0 0 12 13 ]
which represents an output solution that is 13 units long. As you can see, the NorthWest corner will always be 1 and the SouthEast corner will always be the length of your path.
You are NOT guaranteed that there will be only one shortest path for the test cases. If there exist multiple shortest paths, you must represent them all. It can easily be shown that the superposition of two shortest paths will never lead to a multi-valued element in the output matrix.
Example
Input maze:
maze = [ 3 2 2 2 3 1 3 2 2 3 1 3 2 3 1 1 1 0 2 0 1 0 2 1 1 ];
Graphical Representation:
+---+---+---+---+---+ | | | + +---+---+---+---+ | | | | + +---+---+---+ + | | | | | + + + +---+ + | | | + + +---+ + + | | | | +---+---+---+---+---+
Solution:
soln = [ 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 7 8 9 10 5 6 0 0 11 ]
Graphical Representation:
+---+---+---+---+---+ | 1 | | + +---+---+---+---+ | 2 | | | + +---+---+---+ + | 3 | | | | + + + +---+ + | 4 | 7 8 9 10 | + + +---+ + + | 5 6 | |11 | +---+---+---+---+---+
Solution Stats
Problem Comments
Solution Comments
Show commentsProblem Recent Solvers50
Suggested Problems
-
6099 Solvers
-
1265 Solvers
-
Matrix indexing with two vectors of indices
721 Solvers
-
172 Solvers
-
477 Solvers
More from this Author56
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!