I have a two dimensional matrix like
A.........
##....##..
.####...##
..........
.......###
B.........
####...###
#...#.###.
Where '.' represents path and '#' represents wall.I have to find the shortest path possible from point A to point B.I am familiar with BFS algorithm and it seems like a reasonable algorithm for the problem. But I find it confusing to apply on the grid.Can anyone suggest implementation of BFS algorithm in this problem with some pseudo-codes ?
The BFS algorithms is basically:
1.Enqueue the source vertex and mark it visited.
2.While the Q is not empty repeat 3 and 4.
3. Perform deque and the for the dequed vertex x, do
4. For all adjacent vertices of x, that are not visited and mark them visited and enqueue them to the Q.
So thats the basic algorithm, if we go step by step its very easy to apply these steps to grid,the only thing that we should be careful is for a cell in a grid there are 8 neighbours possible, and we must check the boundary conditions before traversing the neighbours, to avoid array index out of bounds.
Say we are at position
A(a,b)
and we want to reachB(c,d)
. We follow the similar 4 steps but with some modification as follows:1.Make a Q of 2-d points,(You can do that easily in languages like Java, by making a class of 2-d points and then Q of objects of that class)
2.Make a 2-d array
visited
of size of grid of type boolean, initialized to false.3.Make a 2-d array
distance
of size of grid of type integer, that will be used for the distance.Let size of grid be
nxm
Now the pseudocode is as follows:
Very basically, think of every dot (
.
) as a node, and every two dots that are neighbors should also have an edge between them*
. This way you get a graph that has all possible places that the path can go through, and it only includes valid edges.From there it's pretty easy to run BFS...
*
If you are allowed to move diagonally, then those edges should also be added. This is already getting into what exactly is the definition of a "neighbor".