Graph
Graph
C
A
B
D E G
Terminologies in Graph data structure
• Vertex (V): Also known as a node, it represents a
single point in the graph. F
• Edge (E): A connection between two vertices. C
• Adjacent Vertices: Two vertices are adjacent if A
they are connected by an edge. B
B
A B C D
A A 1 1 1
B 1 1
C
C 1 1
D 1
D
• The adjacency matrix above represents an undirected Graph, so the values '1'
only tells us where the edges are. Also, the values in the adjacency matrix is
symmetrical because the edges go both ways (undirected Graph).
3 B
A B C D
A
2 1 A 3 2
B
4 C
C 1
D D 4
Adjacency List Graph Representation
A
0 A 3 1 2 null
C 1 B 0 2 null
2 C 1 0 null
D 3 D 0 null
3 B
0 A 1, 3 2, 2 null
A
1 1 B null
2
2 C 1, 1 null
4 C
3 D 0, 4 null
D
Graph Traversal
The two most common ways a Graph can be traversed are:
• Depth First Search (DFS)
• Breadth First Search (BFS)
Depth First Search Traversal
A
B
D E G
Result: D,A,C,B,F,E,G
Breadth First Search Traversal
• DFS use Queue DS
Algorithm Steps
1. Create an empty queue.
2. Enqueue the starting node.
3. Mark the starting node as visited
4. While the queue is not empty:
- Dequeue a node.
- Visit the node.
- Enqueue all unvisited neighbors of the node.
- Mark the neighbors as visited.
F
A
B
D E G
Result: D,A,C,E,B,F,G