Mark As Completed Discussion

Graph Representation

There are several ways to represent a graph in code, one common method is using an adjacency matrix. An adjacency matrix is a 2-dimensional matrix where the cell (i, j) represents the presence or absence of an edge between vertices i and j.

Here's an example of how you can represent a graph using an adjacency matrix in C++:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  // Adjacency Matrix representation of a graph
6  int V = 4; // Number of vertices
7
8  // Create a 2D array of size VxV
9  int graph[V][V];
10
11  // Initialize all elements to 0
12  for (int i = 0; i < V; i++) {
13    for (int j = 0; j < V; j++) {
14      graph[i][j] = 0;
15    }
16  }
17
18  // Add edges to the graph
19  graph[0][1] = 1;
20  graph[1][0] = 1;
21  graph[1][2] = 1;
22  graph[2][1] = 1;
23  graph[2][3] = 1;
24  graph[3][2] = 1;
25
26  // Print the adjacency matrix
27  cout << "Adjacency Matrix:" << endl;
28  for (int i = 0; i < V; i++) {
29    for (int j = 0; j < V; j++) {
30      cout << graph[i][j] << " ";
31    }
32    cout << endl;
33  }
34
35  return 0;
36}

In this example, we have a graph with 4 vertices and 4 edges. The adjacency matrix is initialized as a 2D array of size 4x4, with all elements initially set to 0. We then add edges to the graph by setting the appropriate cells of the matrix to 1. Finally, we print the adjacency matrix to visualize the graph representation.

The adjacency matrix representation works well for graphs with a small number of vertices, but it can become inefficient for large graphs. Another common method of representing graphs is using an adjacency list, which we will explore in the next lesson.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment