the shortest path problem - mazes

i will make a problemset for this later (maybe)

bfs animation 1

bfs animation 2

 

the rest of the page will use these as sample inputs. 3 is the number of rows, 6 is the number of columns per row, # is a wall, . is a path, S is the start, E is the end.

sample input 1

sample input 2

problem A: output whether you can get from S to E

sample output 1

sample output 2

approach:

java solution

python solution

c++ solution

* none of this code has been tested against rigorous data, if there are problems with it lmk

problem B: output the length of the shortest path from S to E

* you can only move up, down, left, right * -1 if no path

sample output 1

sample output 2

in the code for problem A, there's a queue for row and a queue for column. one way to do problem B is to create a third queue for distance - initialize with 0 and push [distance of old node] + 1 for every new node.

practice problem

problem C: output the shortest sequence of moves (up down left right) from S to E

* X if no path

sample output 1

sample output 2

one way is to make a variable mapping from [NODE] to [whichever node NODE came from]. after the BFS finds E, retrace the path by going through the map, e.g. E came from [a node], [a node] came from [another node], [another node] came from S. from these, you can figure out the steps it took to get from S to E.

in Python and C++, you can map from tuple to tuple or std::pair<int,int> to std::pair<int,int>, respectively. in Java you might want to use the java.awt.Point class or make your own thing to store two ints.