图的深度优先遍历和广度优先遍历代码
时间: 2023-12-25 16:28:10 浏览: 98
图的深度优先和广度优先遍历源码
以下是JavaScript实现图的深度优先遍历和广度优先遍历的代码:
深度优先遍历:
```javascript
function dfs(node) {
if (!node) return;
console.log(node.val);
node.visited = true;
for (let i = 0; i < node.neighbors.length; i++) {
const neighbor = node.neighbors[i];
if (!neighbor.visited) {
dfs(neighbor);
}
}
}
```
广度优先遍历:
```javascript
function bfs(node) {
if (!node) return;
const queue = [node];
node.visited = true;
while (queue.length) {
const curr = queue.shift();
console.log(curr.val);
for (let i = 0; i < curr.neighbors.length; i++) {
const neighbor = curr.neighbors[i];
if (!neighbor.visited) {
neighbor.visited = true;
queue.push(neighbor);
}
}
}
}
```
阅读全文