A graph $G = (V, E)$ consists of
Example. $V = {1, 2, 3, 4, 5, 6}$, $E = {(1, 2), (1, 4), (2, 3), (2, 4), (2, 7), (3, 4), (3, 5), (4, 5), (5, 6)}$
Map<E, List<E>>
gives List
of neighbors for each vertex
How to build & use graphs?
boolean adjacent(u, v)
return true
if u
and v
are adjacent (i.e., (u, v)
is an edge)neighbors(u)
return a List
of vertices adjacent to u
addVertex(u)
add a vertex to set of vertices, if not already presentremoveVertex(u)
remove u
and edges containing u
from graphaddEdge(u, v)
add an edge from u
to v
if not already presentremoveEdge(u, v)
remove edge from u
to v
if present(Can have others too…)
Problem. Given a starting vertex $v$, determine if there is a path from $v$ to a given vertex $u$.
Idea. Start at $v$, and walk until you’ve either explored whole graph or find $u$
When visiting a node:
Question. How do we know if search has failed?
What information do we need to maintain to perform DFS?
What ADTs/DSs could we use to maintain that information?
Set<E> visited
of visited nodesStack<E> active
of active nodesboolean dfsFind(E v, E u) {
visited.add(v);
active.push(v)
while (active.size() > 0) {
E cur = active.peek();
if (cur.equals(u)) return true;
for (x : cur.neighbors()) {
if (!visited.contains(x)) {
visited.add(x);
active.push(x);
break;
}
}
}
return false;
}
How could we modify dfsFind
to return the path from v
to u
(if found)?
What might be undesireable about the path found by DFS?
How could we find the shortest path from v
to u
(if any)?
Idea. Start at $v$, and look at other nodes in order of increasing distance from $v$
Question. How to do this?
What information do we need to maintain to perform BFS?
What ADTs/DSs could we use to maintain that information?
Set<E> visited
of visited nodesQueue<E> active
of active nodesboolean bfsFind(E v, E u) {
visited.add(v);
active.push(v)
while (active.size() > 0) {
E cur = active.remove();
if (cur.equals(u)) return true;
for (x : cur.neighbors()) {
if (!visited.contains(x)) {
visited.add(x)
active.add(x);
}
}
}
return false;
}
Why does BFS find u
along the shortest path from v
to u
?
How could we modify bfsFind
to return the shortest path from v
to u
?
Properties of Social Networks:
vertices in well-connected clusters
max distance between nodes is small
What is the “typical” distance between nodes in the network
Empirical investigation!