Can one walk the city crossing every bridge once and only
once?
Euler answered "No." Why?
View the land as vertices. The bridges are edges. There is
an Eulerian walk on a graph only if it is connected
and has either zero or two edges of odd degree.
Graph theory was born to solve a problem of movement in space.
But it is also used for:
Elements:
There are two standard representations:
Consider the following graph:
Following our text, we will prefer adjancency lists.
But, as CLRS point out, in an especially dense graph,
or when we need to detect an edge quickly, we might
prefer a matrix.
Here are the two different representations of this
graph:
Adjacency list:
Adjacency matrix:
For the adjancency matrix:
Both forms can be used to represent directed,
undirected, and weighted graphs.
For weighted graphs, we can store 0 or the weight
in the matrix instead of just 0 or 1.
For the list, we store a tuple (vertex, weight)
in the adjancency list of a vertex.
For directed graphs, in a list, i,
say, would have an entry for j,
but j would not for i.
In a matrix, m[i][j] would be 1,
but m[j][i] would be 0.
For pseudo-code, we just represent attribute f of
edge (u, v) as (u, v).f. (f might
represent the edge already having been visited, for
instance.)
In a real program, there are many, many ways to store
additional information. How to best do this will very much
depend on your application. I have found this can work:
We assume a source vertex s.
We then find every vertex at distance 1 from the
source. (Connected by a direct edge.)
Then we process those vertices, finding every vertex at
distance 2 from the source vertex.
We continue in the same fashion until we run out of
vertices.
Coloring vertices:
Vertices start out "white."
They are colored gray when they are discovered.
They are colored black when all of their adjacent vertices
have been discovered.
Breadth-first search computes shortest path distances.
Lemma 22.1
For any edge (u, v) ∈ E,
δ(s, v) ≤ δ(s, u) + 1
This search goes as "deep" as it can before it ventures
back up the graph to explore other nodes nearer the
source.
Coloring vertices:
Vertices start out "white."
They are colored gray when they are discovered.
They are colored black when they are "finished,"
meaning when all of the nodes on their adjacency list
have been completely explored.
Running time: O(V + E)
Types of edges:
In DFS, when we first explore (u, v) the color of v tells us:
Can only be performed on directed acyclical graphs (DAGs).
The sort makes no sense on undirected graphs or cyclical
graphs.
Property: If G contains an edge (u, v),
then u appears before v
in the topological ordering.
Our book's topological sort algorithm is somewhat weird:
TOPOLOGICAL-SORT(G)
These are components of directed graphs that can each
be reached from the other.
Many advanced graph algorithms rely on de-composing a
graph into strongly directed components, and then
processing those, and then combining the results:
divide-and-conquer!
Algorithm: