# 26.萌时-查找依赖关系中的所有独立循环依赖

function findCycles(graph) {
    const cycles = [];
    const visited = new Set();
    const path = [];

    function visit(vertex) {
        visited.add(vertex);
        path.push(vertex);
        for (let neighbour of graph[vertex]) {
            if (!visited.has(neighbour)) {
                visit(neighbour);
            } else if (path.includes(neighbour)) {
                cycles.push(path.slice(path.indexOf(neighbour)));
            }
        }
        path.pop();
    }

    for (let vertex in graph) {
        if (!visited.has(vertex)) {
            visit(vertex);
        }
    }

    return cycles;
}

// Test the function
const graph = {
    'A': ['B'],
    'B': ['C'],
    'C': ['A', 'D'],
    'D': ['E'],
    'E': ['F'],
    'F': ['D']
};

console.log(findCycles(graph));

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
38
39
Last Updated: 6/3/2024, 1:08:34 AM