|
| 1 | +export default function runTopologicalSortDFS(nodes, edges) { |
| 2 | + const adjList = {}; |
| 3 | + const visited = {}; |
| 4 | + const topoOrder = []; |
| 5 | + const steps = []; |
| 6 | + let hasCycle = false; |
| 7 | + |
| 8 | + // Initialize adjacency list |
| 9 | + nodes.forEach(node => { |
| 10 | + adjList[node] = []; |
| 11 | + visited[node] = 0; // 0 = unvisited, 1 = visiting, 2 = visited |
| 12 | + }); |
| 13 | + |
| 14 | + // Build graph |
| 15 | + edges.forEach(({ from, to }) => { |
| 16 | + adjList[from].push(to); |
| 17 | + }); |
| 18 | + |
| 19 | + function dfs(node) { |
| 20 | + if (hasCycle) return; // stop early if cycle found |
| 21 | + visited[node] = 1; |
| 22 | + steps.push({ |
| 23 | + type: "visit", |
| 24 | + node, |
| 25 | + status: "visiting", |
| 26 | + message: `Visiting ${node}` |
| 27 | + }); |
| 28 | + |
| 29 | + for (const neighbor of adjList[node]) { |
| 30 | + if (visited[neighbor] === 0) { |
| 31 | + steps.push({ |
| 32 | + type: "exploreEdge", |
| 33 | + from: node, |
| 34 | + to: neighbor, |
| 35 | + message: `Exploring edge ${node} → ${neighbor}` |
| 36 | + }); |
| 37 | + dfs(neighbor); |
| 38 | + } else if (visited[neighbor] === 1) { |
| 39 | + // Back edge → cycle detected |
| 40 | + hasCycle = true; |
| 41 | + steps.push({ |
| 42 | + type: "cycleDetected", |
| 43 | + from: node, |
| 44 | + to: neighbor, |
| 45 | + message: `Cycle detected via ${node} → ${neighbor}` |
| 46 | + }); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + visited[node] = 2; |
| 51 | + topoOrder.push(node); |
| 52 | + steps.push({ |
| 53 | + type: "addToTopoOrder", |
| 54 | + node, |
| 55 | + topoOrder: [...topoOrder], |
| 56 | + message: `Added ${node} to topo order` |
| 57 | + }); |
| 58 | + } |
| 59 | + |
| 60 | + // Run DFS for all unvisited nodes |
| 61 | + for (const node of nodes) { |
| 62 | + if (visited[node] === 0) { |
| 63 | + steps.push({ |
| 64 | + type: "startDFS", |
| 65 | + node, |
| 66 | + message: `Starting DFS from ${node}` |
| 67 | + }); |
| 68 | + dfs(node); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + if (!hasCycle) { |
| 73 | + topoOrder.reverse(); // reverse for correct topological order |
| 74 | + steps.push({ |
| 75 | + type: "finalOrder", |
| 76 | + topoOrder: [...topoOrder], |
| 77 | + message: `Topological sort completed successfully` |
| 78 | + }); |
| 79 | + } else { |
| 80 | + steps.push({ |
| 81 | + type: "finalCycle", |
| 82 | + message: `Topological sort failed — cycle exists in graph` |
| 83 | + }); |
| 84 | + } |
| 85 | + |
| 86 | + return steps; |
| 87 | +} |
0 commit comments