lecture8_v2
lecture8_v2
Orient Point
vertices - cities
Riverhead
edges - roads
Shelter Island
Montauk
Islip Sag Harbor
Electronic Circuits
In an electronic circuit, with junctions as vertices as
components as edges.
vertices: junctions
edges: components
Other Graphs/Networks
• Social networks
• The World Wide-Web
• Control flow within a computer program
• Pairwise similarities between items
Flavors of Graphs
The first step in any graph problem is determining which
flavor of graph you are dealing with.
Learning to talk the talk is an important part of walking the
walk.
The flavor of graph has a big impact on which algorithms are
appropriate and efficient.
Directed vs. Undirected Graphs
A graph G = (V, E) is undirected if edge (x, y) ∈ E implies
that (y, x) is also in E.
undirected directed
5 4 7
12
unweighted weighted
simple non−simple
sparse dense
cyclic acyclic
2 1 5 4 3
3 2 4
3
4 5 2 3
5 4 5 1 2 4
To test if edge (i, j) is in the graph, we search the ith list for
j, which takes O(di), where di is the degree of the ith vertex.
Note that di can be much less than n when the graph is sparse.
If necessary, the two copies of each edge can be linked by a
pointer to facilitate deletions.
Tradeoffs Between Adjacency Lists and
Adjacency Matrices
Comparison Winner
Faster to test if (x, y) exists? matrices
Faster to find vertex degree? lists
Less memory on small graphs? lists (m + n) vs. (n2 )
Less memory on big graphs? matrices (small win)
Edge insertion or deletion? matrices O(1)
Faster to traverse the graph? lists m + n vs. n2
Better for most problems? lists
import networkx as nx
myGraph = nx.Graph()
myGraph.add_nodes_from(range(1,5))
myGraph.add_edges_from([(1,2),(1,3),(4,2)])