Graph and its representations

Graph is a data structure that consists of following two components:
1. A finite set of vertices also called as nodes.
2. A finite set of ordered pair of the form (u, v) called as edge. The pair is ordered because (u, v) is not same as (v, u) in case of directed graph(di-graph). The pair of form (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost.

Graphs are used to represent many real life applications: Graphs are used to represent networks. The networks may include paths in a city or telephone network or circuit network. Graphs are also used in social networks like linkedIn, facebook. For example, in facebook, each person is represented with a vertex(or node). Each node is a structure and contains information like person id, name, gender and locale. This can be easily viewed by http://graph.facebook.com/barnwal.aashish where barnwal.aashish is the profile name. See this for more applications of graph.

Following is an example undirected graph with 5 vertices.

Following two are the most commonly used representations of graph.
1. Adjacency Matrix
2. Adjacency List
There are other representations also like, Incidence Matrix and Incidence List. The choice of the graph representation is situation specific. It totally depends on the type of operations to be performed and ease of use.

Adjacency Matrix:
Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. Adjacency matrix for undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w.

The adjacency matrix for the above example graph is:

Adjacency Matrix Representation

Adjacency Matrix Representation of the above graph

Pros: Representation is easier to implement and follow. Removing an edge takes O(1) time. Queries like whether there is an edge from vertex ‘u’ to vertex ‘v’ are efficient and can be done O(1).

Cons: Consumes more space O(V^2). Even if the graph is sparse(contains less number of edges), it consumes the same space. Adding a vertex is O(V^2) time.



Adjacency List:
An array of linked lists is used. Size of the array is equal to number of vertices. Let the array be array[]. An entry array[i] represents the linked list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be stored in nodes of linked lists. Following is adjacency list representation of the above graph.

Adjacency List Representation of Graph

Adjacency List Representation of the above Graph

Below is C code for adjacency list representation of an undirected graph:

// A C Program to demonstrate adjacency list representation of graphs

#include <stdio.h>
#include <stdlib.h>

// A structure to represent an adjacency list node
struct AdjListNode
{
    int dest;
    struct AdjListNode* next;
};

// A structure to represent an adjacency liat
struct AdjList
{
    struct AdjListNode *head;  // pointer to head node of list
};

// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
    int V;
    struct AdjList* array;
};

// A utility function to create a new adjacency list node
struct AdjListNode* newAdjListNode(int dest)
{
    struct AdjListNode* newNode =
            (struct AdjListNode*) malloc(sizeof(struct AdjListNode));
    newNode->dest = dest;
    newNode->next = NULL;
    return newNode;
}

// A utility function that creates a graph of V vertices
struct Graph* createGraph(int V)
{
    struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
    graph->V = V;

    // Create an array of adjacency lists.  Size of array will be V
    graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));

     // Initialize each adjacency list as empty by making head as NULL
    int i;
    for (i = 0; i < V; ++i)
        graph->array[i].head = NULL;

    return graph;
}

// Adds an edge to an undirected graph
void addEdge(struct Graph* graph, int src, int dest)
{
    // Add an edge from src to dest.  A new node is added to the adjacency
    // list of src.  The node is added at the begining
    struct AdjListNode* newNode = newAdjListNode(dest);
    newNode->next = graph->array[src].head;
    graph->array[src].head = newNode;

    // Since graph is undirected, add an edge from dest to src also
    newNode = newAdjListNode(src);
    newNode->next = graph->array[dest].head;
    graph->array[dest].head = newNode;
}

// A utility function to print the adjacenncy list representation of graph
void printGraph(struct Graph* graph)
{
    int v;
    for (v = 0; v < graph->V; ++v)
    {
        struct AdjListNode* pCrawl = graph->array[v].head;
        printf("\n Adjacency list of vertex %d\n head ", v);
        while (pCrawl)
        {
            printf("-> %d", pCrawl->dest);
            pCrawl = pCrawl->next;
        }
        printf("\n");
    }
}

// Driver program to test above functions
int main()
{
    // create the graph given in above fugure
    int V = 5;
    struct Graph* graph = createGraph(V);
    addEdge(graph, 0, 1);
    addEdge(graph, 0, 4);
    addEdge(graph, 1, 2);
    addEdge(graph, 1, 3);
    addEdge(graph, 1, 4);
    addEdge(graph, 2, 3);
    addEdge(graph, 3, 4);

    // print the adjacency list representation of the above graph
    printGraph(graph);

    return 0;
}

Output:

 Adjacency list of vertex 0
 head -> 4-> 1

 Adjacency list of vertex 1
 head -> 4-> 3-> 2-> 0

 Adjacency list of vertex 2
 head -> 3-> 1

 Adjacency list of vertex 3
 head -> 4-> 2-> 1

 Adjacency list of vertex 4
 head -> 3-> 1-> 0

Pros: Saves space O(|V|+|E|) . In the worst case, there can be C(V, 2) number of edges in a graph thus consuming O(V^2) space. Adding a vertex is easier.

Cons: Queries like whether there is an edge from vertex u to vertex v are not efficient and can be done O(V).

Reference:
http://en.wikipedia.org/wiki/Graph_%28abstract_data_type%29

This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.





  • webout
  • Ashish Tilokani

    “Adding a vertex is O(V^2) time” in adjacency matrix. How?

  • Himanshu Dagar

    very simple implementation and easy implementation of above code in c++

    i wrote it at below link :

    http://ideone.com/klAAwE

  • deba

    why array[i].head?? why not array[i]->head!! please Explain

    • Isha

      g->array[i] represents the structure AdjList not the pointer to structure AdjList. In the later case, the graph structure would have to be like this:
      struct Graph
      {
      int V;
      struct AdjList** array;
      };
      Pointer(it denotes the array of) to pointer to AdjList.
      As g->array[i] refers to the structure AdjList not to the pointer to structure AdjList, hence we access it using dot operator.
      Hope it helps.

  • dagar

    (Y)

  • himanshu dagar

    good artical

  • Zheng Luo

    I think there is also another representation called the object and pointers. It is very like the adjacent list though.

  • Sanket

    Why do we need a pointer to the graph and then dynamically allocate memory to it? We can do by using a simple structure object of struct graph instead.. https://ideone.com/ZZ17Yq

    • Anzal

      It is more convenient to make changes in your structure when u pass them through pointers

    • Anzal

      It is more convenient to make changes in your structure when u pass them through pointers

  • Sanket

    Why do we need a pointer to the graph and then dynamically allocate memory to it? We can do by using a simple structure object of struct graph instead.. https://ideone.com/ZZ17Yq

  • xyz
  • abhatnag

    More efficient code in C++ using classes
    http://ideone.com/ih7CQl

  • amaan

    Thanku for the code,
    Is it necessary to use the struct adjlist
    When (i think ) we can do without?

  • pihu

    Does it work with conditions on the 2 vertices?? (I tried doing. I’m getting self-loops for all the vertices.) My output for V=10 shows
    0-> 0->0->0->
    1->1

  • AMIT

    Pros of adjacency matrix- Unlike adjacency list,a single bit is enough to represent whether there is an edge between two vertex or not. In adjacency list,vertex info and next vertex’s link has to be kept

  • B

    why do i get the error of declaration is not allowed here in function createGraph—i haven’t changed anything! Please let me know asap!

    • http://www.facebook.com/barnwal.aashish Aashish

      The program is working fine on ideone. See here: http://ideone.com/Vog8Er
      Can you please tell us which compiler you are using?

      • B

        I have used both g++, borlandc und turbo c lite…i get this error…why? What other compiler should i use? thks

         
        /* Paste your code here (You may delete these lines if not writing code) */
         
        • kartik

          Save your file as .cpp

          • B

            thks so much– it solved the problem, i saw at the beginning of the program that it’s a c-program, but it wroks now with the .cpp-are there any other programs with graphs like these? thks again

             
            /* Paste your code here (You may delete these lines if not writing code) */
             
          • hgtyu

            #include
            #include
            #include

            // A structure to represent a node in adjacency list
            struct AdjListNode
            {
            int dest;
            int weight;
            struct AdjListNode* next;
            };

            // A structure to represent an adjacency liat
            struct AdjList
            {
            struct AdjListNode *head; // pointer to head node of list
            };

            // A structure to represent a graph. A graph is an array of adjacency lists.
            // Size of array will be V (number of vertices in graph)
            struct Graph
            {
            int V;
            struct AdjList* array;
            };

            // A utility function to create a new adjacency list node
            struct AdjListNode* newAdjListNode(int dest, int weight)
            {
            struct AdjListNode* newNode =
            (struct AdjListNode*) malloc(sizeof(struct AdjListNode));
            newNode->dest = dest;
            newNode->weight = weight;
            newNode->next = NULL;
            return newNode;
            }

            // A utility function that creates a graph of V vertices
            struct Graph* createGraph(int V)
            {
            struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
            graph->V = V;

            // Create an array of adjacency lists. Size of array will be V
            graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));

            // Initialize each adjacency list as empty by making head as NULL
            for (int i = 0; i array[i].head = NULL;

            return graph;
            }

            // Adds an edge to an undirected graph
            void addEdge(struct Graph* graph, int src, int dest, int weight)
            {
            // Add an edge from src to dest. A new node is added to the adjacency
            // list of src. The node is added at the begining
            struct AdjListNode* newNode = newAdjListNode(dest, weight);
            newNode->next = graph->array[src].head;
            graph->array[src].head = newNode;

            // Since graph is undirected, add an edge from dest to src also
            newNode = newAdjListNode(src, weight);
            newNode->next = graph->array[dest].head;
            graph->array[dest].head = newNode;
            }

            // Structure to represent a min heap node
            struct MinHeapNode
            {
            int v;
            int dist;
            };

            // Structure to represent a min heap
            struct MinHeap
            {
            int size; // Number of heap nodes present currently
            int capacity; // Capacity of min heap
            int *pos; // This is needed for decreaseKey()
            struct MinHeapNode **array;
            };

            // A utility function to create a new Min Heap Node
            struct MinHeapNode* newMinHeapNode(int v, int dist)
            {
            struct MinHeapNode* minHeapNode =
            (struct MinHeapNode*) malloc(sizeof(struct MinHeapNode));
            minHeapNode->v = v;
            minHeapNode->dist = dist;
            return minHeapNode;
            }

            // A utility function to create a Min Heap
            struct MinHeap* createMinHeap(int capacity)
            {
            struct MinHeap* minHeap =
            (struct MinHeap*) malloc(sizeof(struct MinHeap));
            minHeap->pos = (int *)malloc(capacity * sizeof(int));
            minHeap->size = 0;
            minHeap->capacity = capacity;
            minHeap->array =
            (struct MinHeapNode**) malloc(capacity * sizeof(struct MinHeapNode*));
            return minHeap;
            }

            // A utility function to swap two nodes of min heap. Needed for min heapify
            void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b)
            {
            struct MinHeapNode* t = *a;
            *a = *b;
            *b = t;
            }

            // A standard function to heapify at given idx
            // This function also updates position of nodes when they are swapped.
            // Position is needed for decreaseKey()
            void minHeapify(struct MinHeap* minHeap, int idx)
            {
            int smallest, left, right;
            smallest = idx;
            left = 2 * idx + 1;
            right = 2 * idx + 2;

            if (left size &&
            minHeap->array[left]->dist array[smallest]->dist )
            smallest = left;

            if (right size &&
            minHeap->array[right]->dist array[smallest]->dist )
            smallest = right;

            if (smallest != idx)
            {
            // The nodes to be swapped in min heap
            MinHeapNode *smallestNode = minHeap->array[smallest];
            MinHeapNode *idxNode = minHeap->array[idx];

            // Swap positions
            minHeap->pos[smallestNode->v] = idx;
            minHeap->pos[idxNode->v] = smallest;

            // Swap nodes
            swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);

            minHeapify(minHeap, smallest);
            }
            }

            // A utility function to check if the given minHeap is ampty or not
            int isEmpty(struct MinHeap* minHeap)
            {
            return minHeap->size == 0;
            }

            // Standard function to extract minimum node from heap
            struct MinHeapNode* extractMin(struct MinHeap* minHeap)
            {
            if (isEmpty(minHeap))
            return NULL;

            // Store the root node
            struct MinHeapNode* root = minHeap->array[0];

            // Replace root node with last node
            struct MinHeapNode* lastNode = minHeap->array[minHeap->size – 1];
            minHeap->array[0] = lastNode;

            // Update position of last node
            minHeap->pos[root->v] = minHeap->size-1;
            minHeap->pos[lastNode->v] = 0;

            // Reduce heap size and heapify root
            –minHeap->size;
            minHeapify(minHeap, 0);

            return root;
            }

            // Function to decreasy dist value of a given vertex v. This function
            // uses pos[] of min heap to get the current index of node in min heap
            void decreaseKey(struct MinHeap* minHeap, int v, int dist)
            {
            // Get the index of v in heap array
            int i = minHeap->pos[v];

            // Get the node and update its dist value
            minHeap->array[i]->dist = dist;

            // Travel up while the complete tree is not hepified.
            // This is a O(Logn) loop
            while (i && minHeap->array[i]->dist array[(i – 1) / 2]->dist)
            {
            // Swap this node with its parent
            minHeap->pos[minHeap->array[i]->v] = (i-1)/2;
            minHeap->pos[minHeap->array[(i-1)/2]->v] = i;
            swapMinHeapNode(&minHeap->array[i], &minHeap->array[(i – 1) / 2]);

            // move to parent index
            i = (i – 1) / 2;
            }
            }

            // A utility function to check if a given vertex
            // ‘v’ is in min heap or not
            bool isInMinHeap(struct MinHeap *minHeap, int v)
            {
            if (minHeap->pos[v] size)
            return true;
            return false;
            }

            // A utility function used to print the solution
            void printArr(int dist[], int n)
            {
            printf(“Vertex Distance from Sourcen”);
            for (int i = 0; i V;// Get the number of vertices in graph
            int dist[V]; // dist values used to pick minimum weight edge in cut

            // minHeap represents set E
            struct MinHeap* minHeap = createMinHeap(V);

            // Initialize min heap with all vertices. dist value of all vertices
            for (int v = 0; v array[v] = newMinHeapNode(v, dist[v]);
            minHeap->pos[v] = v;
            }

            // Make dist value of src vertex as 0 so that it is extracted first
            minHeap->array[src] = newMinHeapNode(src, dist[src]);
            minHeap->pos[src] = src;
            dist[src] = 0;
            decreaseKey(minHeap, src, dist[src]);

            // Initially size of min heap is equal to V
            minHeap->size = V;

            // In the followin loop, min heap contains all nodes
            // whose shortest distance is not yet finalized.
            while (!isEmpty(minHeap))
            {
            // Extract the vertex with minimum distance value
            struct MinHeapNode* minHeapNode = extractMin(minHeap);
            int u = minHeapNode->v; // Store the extracted vertex number

            // Traverse through all adjacent vertices of u (the extracted
            // vertex) and update their distance values
            struct AdjListNode* pCrawl = graph->array[u].head;
            while (pCrawl != NULL)
            {
            int v = pCrawl->dest;

            // If shortest distance to v is not finalized yet, and distance to v
            // through u is less than its previously calculated distance
            if (isInMinHeap(minHeap, v) && dist[u] != INT_MAX &&
            pCrawl->weight + dist[u] weight;

            // update distance value in min heap also
            decreaseKey(minHeap, v, dist[v]);
            }
            pCrawl = pCrawl->next;
            }
            }

            // print the calculated shortest distances
            printArr(dist, V);
            }

            // Driver program to test above functions
            int main()
            {
            // create the graph given in above fugure
            int V = 9;
            struct Graph* graph = createGraph(V);
            addEdge(graph, 0, 1, 4);
            addEdge(graph, 0, 7, 8);
            addEdge(graph, 1, 2, 8);
            addEdge(graph, 1, 7, 11);
            addEdge(graph, 2, 3, 7);
            addEdge(graph, 2, 8, 2);
            addEdge(graph, 2, 5, 4);
            addEdge(graph, 3, 4, 9);
            addEdge(graph, 3, 5, 14);
            addEdge(graph, 4, 5, 10);
            addEdge(graph, 5, 6, 2);
            addEdge(graph, 6, 7, 1);
            addEdge(graph, 6, 8, 6);
            addEdge(graph, 7, 8, 7);

            dijkstra(graph, 0);

            return 0;
            }

          • kartik

            You seem to be using non-standard turbo C compiler. It works fine any C99 standard compiler.

  • piyush

    very nice article

     
    /* Paste your code here (You may delete these lines if not writing code) */