Adjacency Matrix
A 2D array (or matrix) used to represent a graph. The rows and columns represent the vertices. A cell in the matrix contains a value (typically 1 or 0) indicating whether there is an edge between the vertices.
Example:
For an undirected graph with vertices A, B, C, D:The adjacency matrix might look like this:
A-B, A-D, B-C, C-D
A B C D
A 0 1 0 1
B 1 0 1 0
C 0 1 0 1
D 1 0 1 0
Pros:
Cons:
Weighted Graphs: Instead of 1, store the weight of the edge in the matrix. For example, a weighted graph might have:The adjacency matrix could look like this:
A-B (4), A-D (2), B-C (5), C-D (1)
A B C D
A 0 4 0 2
B 4 0 5 0
C 0 5 0 1
D 2 0 1 0
Adjacency List
A more space-efficient way to represent a graph, particularly for sparse graphs. Each vertex has a list of vertices it is connected to.
Example:
For the same undirected graph as above:
A -> B, D
B -> A, C
C -> B, D
D -> A, C
Ps:
Cons:
Weighted Graphs: Store pairs (neighbor vertex, weight) in the adjacency list. For example:
A -> (B, 4), (D, 2)
B -> (A, 4), (C, 5)
C -> (B, 5), (D, 1)
D -> (A, 2), (C, 1)
BFS explores a graph layer by layer, starting from a source vertex and visiting all its neighbors before moving on to the next level of neighbors.
Algorithm:
Example:
For a graph starting at vertex A with neighbors B and C, and B having a neighbor D:Result: A -> B -> C -> D
Start at A -> Visit B, C -> Visit D (from B)
Pros:
Time Complexity: O(V + E)
Space Complexity: O(V)
Applications: