forked from TamimEhsan/AlgorithmVisualizer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.jsx
More file actions
35 lines (32 loc) · 1.17 KB
/
Copy pathbfs.jsx
File metadata and controls
35 lines (32 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
export function bfsdfs(grid,startNode,endNode,algo){
var list = [];
const nodesInOrder = [];
nodesInOrder.push(startNode);
list.push(startNode);
startNode.isVisited = true;
while(!!list.length){
const currentNode = (algo === "bfs" ? list.shift():list.pop());
nodesInOrder.push(currentNode);
if( currentNode === endNode ) return nodesInOrder;
if( algo === "dfs" ) currentNode.isVisited = true;
const nodesToPush = getNeighbours(grid,currentNode);
for( const node of nodesToPush ){
if(algo === "bfs"){
node.isVisited = true;
}
node.previousNode = currentNode;
list.push(node);
}
}
return nodesInOrder;
}
function getNeighbours(grid,node){
const neighbors = [];
const {col, row} = node;
// console.log(node);
if (col > 0) neighbors.push(grid[row][col - 1]);
if (row > 0) neighbors.push(grid[row - 1][col]);
if (row < grid.length - 1) neighbors.push(grid[row + 1][col]);
if (col < grid[0].length - 1) neighbors.push(grid[row][col + 1]);
return neighbors.filter(neighbor => (!neighbor.isVisited && !neighbor.isWall ));
}