Topological Sort

语言

Implement a function that performs a topological sort on a directed graph (in adjacency list format), where each key represents a node and its value is an array of nodes reached by outgoing edges from that node.

Return an array containing every node such that, for each directed edge from A to B, A appears before B. Return an empty array when the graph is empty or contains a cycle.

When multiple nodes have no remaining incoming edges, process them in first-in, first-out discovery order. Initially discover nodes in object-key order, and discover newly available neighbors in their adjacency-array order.

Examples

const graph1 = {
A: ['B', 'C'],
B: ['C', 'D', 'E'],
C: ['F'],
D: [],
E: ['F'],
F: [],
};
topologicalSort(graph1); // ['A', 'B', 'C', 'D', 'E', 'F']
const graph2 = {
A: ['B', 'C'],
B: ['C', 'D'],
C: ['D'],
D: ['E'],
E: ['F'],
F: [],
};
topologicalSort(graph2); // ['A', 'B', 'C', 'D', 'E', 'F']
const graph3 = {
A: [],
B: ['A'],
C: ['B'],
D: ['C'],
E: ['D'],
F: ['E'],
};
topologicalSort(graph3); // ['F', 'E', 'D', 'C', 'B', 'A']

A Queue data structure is also provided for you at the bottom of the skeleton code.

Hints

新

在这些公司提问

Unlock company signalsPremium shows which companies ask this question so you can prioritize practice by target company.
Unlock

加载编辑器

    Topological Sort | 算法面试题及解决方案