Topological Sort
It is a linear ordering of nodes of a DAG(Directed Acyclic Graph) such that for every directed edge (u -> v), node u comes before v.
Example
An adjacency list represents a graph.
const adj = [
[], // 0
[], // 1
[3], // 2 -> 3
[1], // 3 -> 1
[0, 1], // 4 -> 0, 1
[0, 2] // 5 -> 0, 2
]
Representation
5, 0, 2, 3, 1, 4
Code
function topologicalSortDFS(n, graph) {
let ans = [];
let visited = new Set();
function dfs(curr) {
visited.add(curr);
for (let neighbor of graph[curr]) {
if (!visited.has(neighbor)) {
dfs(neighbor);
}
}
ans.push(curr);
}
for (let i = 0; i < n; i++) {
if (!visited.has(i)) {
dfs(i);
}
}
return ans.reverse();
}
const n = 6;
const adj = [
[], // 0
[], // 1
[3], // 2 -> 3
[1], // 3 -> 1
[0, 1], // 4 -> 0, 1
[0, 2] // 5 -> 0, 2
];
console.log(topologicalSortDFS(n, adj));
def topological_sort_dfs(n, graph):
visited = [False] * n
ans = []
def dfs(curr):
visited[curr] = True
for neighbor in graph[curr]:
if not visited[neighbor]:
dfs(neighbor)
ans.append(curr)
for i in range(n):
if not visited[i]:
dfs(i)
return ans[::-1]
n = 6
adj = [
[], # 0
[], # 1
[3], # 2 -> 3
[1], # 3 -> 1
[0, 1], # 4 -> 0, 1
[0, 2] # 5 -> 0, 2
]
print(topological_sort_dfs(n, adj))
import java.util.*;
class Solution {
static void dfs(int curr,
List> graph,
boolean[] visited,
List ans) {
visited[curr] = true;
for (int neighbor : graph.get(curr)) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited, ans);
}
}
ans.add(curr);
}
static List topologicalSort(int n, List> graph) {
boolean[] visited = new boolean[n];
List ans = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i, graph, visited, ans);
}
}
Collections.reverse(ans);
return ans;
}
public static void main(String[] args) {
int n = 6;
List> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
graph.get(2).add(3);
graph.get(3).add(1);
graph.get(4).add(0);
graph.get(4).add(1);
graph.get(5).add(0);
graph.get(5).add(2);
System.out.println(topologicalSort(n, graph));
}
}
#include <bits/stdc++.h>
using namespace std;
void dfs(
int curr,
vector>& graph,
vector& visited,
vector& ans
) {
visited[curr] = true;
for (int neighbor : graph[curr]) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited, ans);
}
}
ans.push_back(curr);
}
vector topologicalSort(int n, vector>& graph) {
vector visited(n, false);
vector ans;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i, graph, visited, ans);
}
}
reverse(ans.begin(), ans.end());
return ans;
}
int main() {
int n = 6;
vector> graph(n);
graph[2].push_back(3);
graph[3].push_back(1);
graph[4].push_back(0);
graph[4].push_back(1);
graph[5].push_back(0);
graph[5].push_back(2);
vector result = topologicalSort(n, graph);
for (int x : result) {
cout << x << " ";
}
return 0;
}
#include <stdio.h>
int graph[6][2] = {
{}, // 0
{}, // 1
{3}, // 2 -> 3
{1}, // 3 -> 1
{0, 1}, // 4 -> 0, 1
{0, 2} // 5 -> 0, 2
};
int size[6] = {0, 0, 1, 1, 2, 2};
int visited[6] = {0};
int ans[6];
int idx = 0;
void dfs(int curr)
{
visited[curr] = 1;
for (int i = 0; i < size[curr]; i++)
{
int neighbor = graph[curr][i];
if (!visited[neighbor])
{
dfs(neighbor);
}
}
ans[idx++] = curr;
}
int main()
{
for (int i = 0; i < 6; i++)
{
if (!visited[i])
{
dfs(i);
}
}
/* Reverse and print result */
for (int i = 5; i >= 0; i--)
{
printf("%d ", ans[i]);
}
return 0;
}
using System;
using System.Collections.Generic;
class Solution
{
static void DFS(
int curr,
List[] graph,
bool[] visited,
List ans)
{
visited[curr] = true;
foreach (int neighbor in graph[curr])
{
if (!visited[neighbor])
{
DFS(neighbor, graph, visited, ans);
}
}
ans.Add(curr);
}
static List TopologicalSort(int n, List[] graph)
{
bool[] visited = new bool[n];
List ans = new List();
for (int i = 0; i < n; i++)
{
if (!visited[i])
{
DFS(i, graph, visited, ans);
}
}
ans.Reverse();
return ans;
}
static void Main()
{
int n = 6;
List[] graph = new List[n];
for (int i = 0; i < n; i++)
{
graph[i] = new List();
}
graph[2].Add(3);
graph[3].Add(1);
graph[4].Add(0);
graph[4].Add(1);
graph[5].Add(0);
graph[5].Add(2);
var result = TopologicalSort(n, graph);
Console.WriteLine(string.Join(" ", result));
}
}
Add A Comment
