图
图是网络结构的抽象模型,是一组由边连接的节点。图可以表示任何二元关系,比如道路、航班。JS 中没有图,但是可以用Object和Array构建图。图的表示法:邻接矩阵、邻接表、关联矩阵。
js
复制代码
// 邻接表表示图结构
const graph = {
0: [1, 2],
1: [2],
2: [0, 3],
3: [3]
}
// 深度优先遍历
const visited = new Set()
function dfs(n, visited) { // n 表示开始访问的根节点
console.log(n)
visited.add(n)
graph[n].forEach((item) => {
if (!visited.has(item)) dfs(item, visited)
})
}
dfs(2, visited) // 2 0 1 3
console.log(visited) // {2, 0, 1, 3}
// 广度优先遍历
function bfs(n) { // n 表示开始访问的根节点
const visited = new Set()
visited.add(n)
const queue = [n]
while (queue.length) {
const shiftVal = queue.shift()
graph[shiftVal].forEach((item) => {
if (!visited.has(item)) {
queue.push(item)
visited.add(item)
}
})
}
console.log(visited) // {2, 0, 3, 1}
}
bfs(2)
使用场景
-
场景一:道路
-
场景二:航班
LeetCode 题目