Graphs
A graph is an irreflexive and symmetric relation.
- A graph is a pair
- The set is the vertices or nodes of
- The set is the edges of
- For every we have - symmetric
- There are no edges - irreflexive
This type of graph is called loop-free undirected graph, referring to irreflexive and symmetric.
Graph Visualization
We usually visualize graphs as a set of points (vertices) connected by line (edges).
Graph Definitions
Neighbors
If then we say and are adjacent. We also say that and are neighbors.
If there is an edge between two vertices then they are adjacent.
The neighborhood of a vertex is the set of neighbors.
The neighborhood of a set of vertices is a set that contains all neighbors of vertices in .
def N(G, u):
"""
Get the neighbors of a vertex.
G: a graph (V, E)
u: a vertex
"""
V, E = G
return {v for v in V if (u, v) in E}
def NS(G, S):
"""
Get the neighbors of a set of vertices.
G: a graph (V, E)
S: a set of vertices
"""
neighbors = set()
for u in S:
neighbors = neighbors.union(N(G, u))
return neighbors
def NS_2(G, S):
V, E = G
return {v for v in V for u in S if (u,v) in E}
# the graph from the visualization section
V = {"A", "B", "C", "D", "E"}
E = {
("A","B"),("B","A"),
("A","C"),("C","A"),
("B","C"),("C","B"),
("B","D"),("D","B"),
("D","E"),("E","D")
}
G = (V, E)
print("Vertices:", V)
print("Edges:", E)
print("Neighbors of A:", N(G, "A"))
print("Neighbors of {A, D}:", NS(G, {"A","D"}))
"""
Vertices: {'D', 'C', 'E', 'A', 'B'}
Edges: {('C', 'B'), ('E', 'D'), ('C', 'A'), ('D', 'E'), ('B', 'A'), ('B', 'C'), ('D', 'B'), ('B', 'D'), ('A', 'C'), ('A', 'B')}
Neighbors of A: {'B', 'C'}
Neighbors of {A, D}: {'B', 'C', 'E'}
"""
Degrees
The degree of a vertex is the size of its neighbors.
Every edge adds 1 to the degree of and the degree of , so we have the sum of degrees:
We count and together as a single edge.
Incident
If , we say is incident with u
(and v
).
Graph Examples
- The set of computers in a network, where and are adjacent if they are connected physically (Ethernet, wifi).
- The set of cities in the world, and are adjacent if there is a direct flight.
Handshaking Lemma
Since the sum of degrees is even, there must be an even number of vertices with odd degree.