Skip to content

Commit 4991c9e

Browse files
committed
Fix Depth First Search ordering
* It is a stack so push last is popped first
1 parent bc455d9 commit 4991c9e

File tree

1 file changed

+6
-14
lines changed

1 file changed

+6
-14
lines changed

src/algorithms/pathfinding/DepthFirstSearch.ts

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,13 @@ import { useMazeStore } from '../../hooks/useMazeStore';
44
// Define a generator function for depth-first search on the maze
55
function* dfsGenerator(maze: Cell[][], startCell: Cell, endCell: Cell): Generator<Cell[][] | Cell[] | null, unknown> {
66
const stack: Cell[] = [];
7-
const visited: boolean[][] = [];
8-
9-
for (let row = 0; row < maze.length; row++) {
10-
visited[row] = [];
11-
for (let col = 0; col < maze[row].length; col++) {
12-
visited[row][col] = false;
13-
}
14-
}
157

168
stack.push(startCell);
17-
visited[startCell.row][startCell.col] = true;
189
maze[startCell.row][startCell.col].visited = true;
1910

2011
while (stack.length > 0) {
2112
const currentCell = stack.pop();
13+
2214
if (!currentCell) {
2315
continue;
2416
}
@@ -32,11 +24,9 @@ function* dfsGenerator(maze: Cell[][], startCell: Cell, endCell: Cell): Generato
3224
let neighbors = getNeighbors(maze, currentCell);
3325

3426
for (let neighbor of neighbors) {
35-
if (!visited[neighbor.row][neighbor.col] && !neighbor.visited) {
27+
if (!neighbor.visited) {
3628
neighbor.prev = currentCell;
3729
stack.push(neighbor);
38-
visited[neighbor.row][neighbor.col] = true;
39-
maze[neighbor.row][neighbor.col].visited = true;
4030
}
4131
}
4232
yield maze;
@@ -72,19 +62,21 @@ export async function DepthFirstSearch(startCell: Cell, endCell: Cell): Promise<
7262
export function getNeighbors(cells: Cell[][], cell: Cell): Cell[] {
7363
const neighbors: Cell[] = [];
7464
const { row, col } = cell;
75-
65+
7666
if (row > 0 && !cells[row - 1][col].wall) {
7767
neighbors.push(cells[row - 1][col]);
7868
}
7969
if (col > 0 && !cells[row][col - 1].wall) {
8070
neighbors.push(cells[row][col - 1]);
8171
}
72+
8273
if (row < cells.length - 1 && !cells[row + 1][col].wall) {
8374
neighbors.push(cells[row + 1][col]);
8475
}
76+
8577
if (col < cells[0].length - 1 && !cells[row][col + 1].wall) {
8678
neighbors.push(cells[row][col + 1]);
8779
}
88-
80+
8981
return neighbors;
9082
}

0 commit comments

Comments
 (0)