I'm trying to implement a breadth first search to solve a maze, but I keep getting stuck in an infinite loop and I have no idea why this is happening. Rows and columns are the number of rows and columns for my maze/grid. I am starting from the top left cell, and checking to see if a neighbour is within the grid before adding them to the queue.
export function elementInGrid<T>(neighbour: number[], rows: number, columns: number): boolean{
const [i, j] = neighbour;
return (0 <= i && i <= rows - 1) && (0 <= j && j <= columns - 1);
}
function arrayEquality<T>(a: T[], b: T[]): boolean{
return a.sort().toString() === b.sort().toString()
}
export const breadthFirstSearch = (rows: number, columns: number) => {
const startPoint = [0, 0];
const endPoint = [rows - 1, columns - 1];
const queue = [startPoint];
while (queue.length > 0){
const [i, j] = queue.shift()!;
if (arrayEquality([i, j], endPoint)){
break
}
const neighbours = [[i - 1, j], [i, j + 1], [i + 1, j], [i, j - 1]]
neighbours.forEach(neighbour => {
if (elementInGrid(neighbour, rows, columns)){
queue.push(neighbour);
}
})
}
}