# 图的深度广度优先遍历

const graph = {
  0: [1, 2],
  1: [2],
  2: [0, 3],
  3: [3],
};

const visited = new Set();
// 深度
const dfs = (n) => {
  console.log(n);
  visited.add(n);
  graph[n].forEach((c) => {
    if (!visited.has(c)) {
      dfs(c);
    }
  });
};

// dfs(2);

const bfs = (n) => {
  const q = [n];

  while (q.length) {
    const v = q.shift();
    visited.add(v);
    console.log(v);
    graph[v].forEach((c) => {
      if (!visited.has(c)) {
        q.push(c);
      }
    });
  }
};

bfs(2);
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
36
37
Last Updated: 7/3/2023, 11:54:34 PM