package main
import (
"fmt"
"math"
)
type Edge struct {
to, weight int
}
func shortestPathDAG(n int, graph [][]Edge, start int) []int {
dist := make([]int, n)
for i := range dist {
dist[i] = math.MaxInt32
}
dist[start] = 0
// Compute in-degree for topological sort
inDegree := make([]int, n)
for u := 0; u < n; u++ {
for _, e := range graph[u] {
inDegree[e.to]++
}
}
// Queue for nodes with zero in-degree
queue := []int{}
for i := 0; i < n; i++ {
if inDegree[i] == 0 {
queue = append(queue, i)
}
}
// Process nodes in topological order
for len(queue) > 0 {
u := queue[0]
queue = queue[1:]
// Relax edges from u
for _, e := range graph[u] {
if dist[u] != math.MaxInt32 && dist[u]+e.weight < dist[e.to] {
dist[e.to] = dist[u] + e.weight
}
inDegree[e.to]--
if inDegree[e.to] == 0 {
queue = append(queue, e.to)
}
}
}
return dist
}
func main() {
n := 5
graph := make([][]Edge, n)
graph[0] = []Edge{{1, 2}, {2, 4}}
graph[1] = []Edge{{2, 1}, {3, 7}}
graph[2] = []Edge{{4, 3}}
graph[4] = []Edge{{3, 2}}
start := 0
dist := shortestPathDAG(n, graph, start)
for i, d := range dist {
if d == math.MaxInt32 {
fmt.Printf("Node %d: unreachable\n", i)
} else {
fmt.Printf("Node %d: %d\n", i, d)
}
}
}
dist := make([]int, n)
for i := range dist {
dist[i] = math.MaxInt32
}
dist[start] = 0
Initialize distances with infinity except start node zero
for u := 0; u < n; u++ {
for _, e := range graph[u] {
inDegree[e.to]++
}
}
Calculate in-degree for each node to find start points
for i := 0; i < n; i++ {
if inDegree[i] == 0 {
queue = append(queue, i)
}
}
Add nodes with zero in-degree to queue for topological order
for len(queue) > 0 {
u := queue[0]
queue = queue[1:]
Process nodes in topological order by removing from queue
for _, e := range graph[u] {
if dist[u] != math.MaxInt32 && dist[u]+e.weight < dist[e.to] {
dist[e.to] = dist[u] + e.weight
}
Relax edges: update shortest distance if better path found
inDegree[e.to]--
if inDegree[e.to] == 0 {
queue = append(queue, e.to)
}
Decrease in-degree and add to queue if zero for next processing
Node 0: 0
Node 1: 2
Node 2: 3
Node 3: 8
Node 4: 6