Skip to content

遍历

js
let bfs = function (graph, start) {
	let queue = [start]
	let visited = new Set()
	visited.add(start)

	while (queue.length > 0) {
		let current = queue.shift()
		console.log(current)

		for (let neighbor of graph[current]) {
			if (!visited.has(neighbor)) {
				queue.push(neighbor)
				visited.add(neighbor)
			}
		}
	}
}
let dfs = function (graph, start) {
	let stack = [start]
	let visited = new Set()
	visited.add(start)

	while (stack.length > 0) {
		let current = stack.pop()
		console.log(current)

		for (let neighbor of graph[current]) {
			if (!visited.has(neighbor)) {
				stack.push(neighbor)
				visited.add(neighbor)
			}
		}
	}
}