So I've implemented a BFS search algorithm to find the shortest path from the first index in the binary matrix (top left) to the last index (bottom right).
I would now like to trace back the path that I found, but I have no idea how to keep track of the parent node and when to actually add it to a data structure.
int[][] dirs = new[]
{
new[] { 0, 1 },
new[] { 1, 1 },
new[] { 1, 0 },
new[] { 1, -1 },
new[] { 0, -1 },
new[] { -1, -1 },
new[] { -1, 0 },
new[] { -1, 1 }
};
public int BinaryMatrix(int[][] grid)
{
var rowLength = grid.Length;
var colLength = grid[0].Length;
if (grid[0][0] == 1 || grid[rowLength - 1][colLength - 1] == 1)
return -1;
var Queue = new Queue<int[]>();
int[][] visited = new int[rowLength][];
for (int i = 0; i < visited.Length; i++)
visited[i] = new int[colLength];
Queue.Enqueue(new[] { 0, 0 });
visited[0][0] = 2;
int steps = 1;
while (Queue.Count != 0)
{
int levelSize = Queue.Count;
for (int r = 0; r < levelSize; r++)
{
int[] coord = Queue.Dequeue();
var cy = coord[0];
var cx = coord[1];
if (cy == rowLength - 1 && cx == colLength - 1)
{
return steps;
}
for (int i = 0; i < dirs.Length; i++)
{
int neighborY = dirs[i][0] + cy;
int neighborX = dirs[i][1] + cx;
if (neighborX >= 0 && neighborX < colLength && neighborY >= 0 && neighborY < rowLength)
{
if (visited[neighborY][neighborX] == 0 &&
grid[neighborY][neighborX] == 0)
{
Queue.Enqueue(new[] { neighborY, neighborX });
visited[neighborY][neighborX] = 2;
}
}
}
}
steps++;
}
return -1;
}
What I have tried:
I've tried keeping track of the parent node but I kept getting every other node as well. So I'm not sure how to.