Home > Articles, Data Structures & Algorithms > Implementation of graph representation with an adjacency matrix.

Implementation of graph representation with an adjacency matrix.

The following program reads a set of edges that define an undirected graph and creates a representation of this graph with an adjacency matrix, giving a[i][j] and a[j][i] the value of 1 if there is an edge from i to j or from j to i in the graph, or the value of 0 if it does not exist. Also, we assume that the number of vertices V is a constant known at compilation time. Otherwise, there should be dynamic memory allocation for the array that represents the adjacency matrix.

You should know that the implementation of the algorithm does not take into account issues of data input validation or proper management of dynamic memory (e.g. avoiding memory leaks) because it is only necessary to highlight the logic of the algorithm.

#include <iostream>
#include <cstdlib>

using namespace std;

const int V = 100;

int
main () {
  bool adj[V][V] = { false };

  int i;
  for (i = 0; i < V; i++)
    adj[i][i] = true;

  int j;
  while (cin >> i >> j)
    adj[i][j] = adj[j][i] = true;

  return EXIT_SUCCESS;
}
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: