Solution:
/* This program sets d[v] to the outdegree of v, for all vertex v. */
for v ← 1 to n do {
d[v] ← 0
for w ← 1 to n do
d[v] ← d[v] + A[v, w]
}
Node
object with a vertex
field and a nextNode
field.LINK
& VERTEX
. They give pointer and vertex information, respectively.LINK[i]
is the head of \(i\)'s adjacency list.LINK[i]
and VERTEX[i]
constitute a node on an adjacency list.
LINK[i]
points to next nodeVERTEX[i]
gives the vertexLINK[i]
= 0 if the node at \(i\) is the last one on its adjacency list.Solution:
/* program sets d[v] to the outdegree of v, for all vertex v */
for v ← 1 to n do {
d[v] ← 0
i ← LINK[v]
while i ≠ 0 do {
d[v] ← d[v] + 1
i ← LINK[i]
}
}
Such an algorithm takes advantage of sparsity since if \(m\) is \(O(n)\) then the time is \(O(n)\).
We usally omit the details of walking down the adjacency list. So the high-level code for the above problem is.
/* Sets d[v] to the outdegree of v, for all vertex v */
for each v ∈ V do {
d[v] ← 0
for each edge (v, w) do
d[v] ← d[v] + 1
}
Exercise: What's wrong with this pseudocode to calculate the indegree of each vertex?
for each v ∈ V do {
d[v] ← 0
for each edge (w, v) do
d[v] ← d[v] + 1
}
MATE[w]
that points to the node \(v\) appearing on the adjacacy list of \(w\), and vice versa. This is required for implementing edge deletion in \(O(1)\) time.