How to Represent Graph Using Incidence Matrix in Java?


In order to represent a graph in Java using an incidence matrix, a data structure containing the relationships between vertices and edges must be built. The incidence matrix is a 2D array where the rows and columns stand in for the vertices and edges, respectively, and the entries represent the connections between them. If there is a "1" at position (i, j), vertex i is incident on edge j. Although it may need more memory for large graphs, this approach permits efficient graph operations, such as the insertion or removal of edges. Programmers can efficiently construct and manipulate graph structures to address many issues in computer science and related fields by creating this data structure in Java.

Incidence Matrix

The relationships between vertices and edges in a graph are represented mathematically by an incidence matrix in graph theory. It is a 2D binary matrix, with columns representing the edges and rows representing the vertices. If vertex i is incident to edge j, the entry at location (i, j) is '1'; otherwise, it is '0'. This matrix effectively represents a graph's structure, making it easier to perform operations like adding and removing edges. It is an important idea in computer science and other disciplines that deal with complicated networks because it provides a key tool for analysing and addressing graph-based problems.

Methods Used

  • Adjacency Matrix

  • Adjacency List

  • Edge List

Adjacency Matrix

An adjacency matrix is a 2D array that is used to express the connections between vertices when creating a graph in Java. If there is an edge linking vertex i and vertex j, it can be seen in the matrix's cell (i, j). A "1" in the cell denotes an edge while a "0" denotes no edge. This matrix is frequently used for dense graphs since it facilitates quick traversal and study of the graph. However, due to its square form, it might be memory-intensive for large graphs. Programmers may efficiently model, analyse, and manipulate graph topologies for a variety of applications by using the adjacency matrix in Java.

Algorithm

  • Determine the graph's vertex count in step one.

  • Construct a [number of vertices] x [number of vertices] 2D array (matrix).

  • Initialise the matrix by setting all entries to 0, which means there are initially no edges.

  • In the graph, set the relevant matrix cells for each edge (i, j) to 1 to symbolise the connection between vertices i and j.

  • Ensure matrix symmetry in undirected graphs since edges (i, j) and (j, i) are identical.

  • Include routines for testing edge presence, locating vertex neighbours, and adding/removing edges.

  • To verify the implementation's accuracy and functionality, test it using sample graphs.

Example

#include <iostream>
#include <vector>

using namespace std;

class Graph {
private:
   int V;
   vector<vector<int>> adjMatrix;

public:
   Graph(int vertices) : V(vertices) {
      adjMatrix.resize(V, vector<int>(V, 0));
   }

   void addEdge(int u, int v) {
      adjMatrix[u][v] = 1;
      adjMatrix[v][u] = 1;
   }

   void printAdjMatrix() {
      for (int i = 0; i < V; ++i) {
         for (int j = 0; j < V; ++j) {
            cout << adjMatrix[i][j] << " ";
         }
         cout << endl;
      }
   }
};

int main() {
   int numVertices = 5;
   Graph graph(numVertices);

   graph.addEdge(0, 1);
   graph.addEdge(0, 4);
   graph.addEdge(1, 2);
   graph.addEdge(1, 3);
   graph.addEdge(1, 4);
   graph.addEdge(2, 3);
   graph.addEdge(3, 4);

   cout << "Adjacency Matrix:\n";
   graph.printAdjMatrix();

   return 0;
}

Output

Adjacency Matrix:
0 1 0 0 1 
1 0 1 1 1 
0 1 0 1 0 
0 1 1 0 1 
1 1 0 1 0 

Adjacency List

An adjacency list is a Java data structure that effectively stores the connections When representing a graph, an adjacency list is a Java data structure that serves to effectively store the relationships between vertices and their adjacent vertices. Each linked list or array that makes up the structure corresponds to a vertex and contains the vertex's neighbours. This approach is appropriate for sparse graphs since it conserves memory by only keeping links that actually exist. Programmers may quickly conduct graph traversals, node addition, and deletion operations by creating an adjacency list in Java, making it a popular option for many graph-related algorithms and applications.

Algorithm

  • It is recommended to store the adjacency list in a data structure. This might be a set of linked lists or an array of ArrayLists, where each element represents a vertex and stores the information about the nearby vertices.

  • Start the adjacency list by adding empty lists or ArrayLists for each vertex in the graph.

  • To add edges between vertices, provide methods in the graph class. By adding the necessary vertices to one another's neighbouring lists, these techniques will update the adjacency list.

  • Add removal methods for edges or vertices if desired, changing the adjacency list as a result.

  • Use the adjacency list in conjunction with graph traversal techniques like depth-first search or breadth-first search to quickly explore all vertices in the graph.

  • To tackle numerous network-related problems and techniques, use the graph representation with the adjacency list in your Java programme.

Example

#include <iostream>
#include <vector>

using namespace std;

class Graph {
private:
   int numVertices;
   vector<vector<int>> adjList;

public:
   Graph(int vertices) : numVertices(vertices), adjList(vertices) {}

   void addEdge(int src, int dest) {
      adjList[src].push_back(dest);
      adjList[dest].push_back(src);
   }

   void printGraph() {
      for (int i = 0; i < numVertices; ++i) {
         cout << "Vertex " << i << " is connected to: ";
         for (int neighbor : adjList[i]) {
            cout << neighbor << " ";
         }
         cout << endl;
      }
   }
};

int main() {
   int numVertices = 5;
   Graph graph(numVertices);

   graph.addEdge(0, 1);
   graph.addEdge(0, 4);
   graph.addEdge(1, 2);
   graph.addEdge(1, 3);
   graph.addEdge(1, 4);
   graph.addEdge(2, 3);
   graph.addEdge(3, 4);

   graph.printGraph();

   return 0;
}

Output

Vertex 0 is connected to: 1 4 
Vertex 1 is connected to: 0 2 3 4 
Vertex 2 is connected to: 1 3 
Vertex 3 is connected to: 1 2 4 
Vertex 4 is connected to: 0 1 3 

Conclusion

For modelling, analysing, and manipulating network structures effectively, Java's representation of a graph using an incidence matrix or an adjacency list offers vital capabilities. Although more memory-intensive, the incidence matrix is appropriate for thick graphs since it makes adding and removing edges simple. The adjacency list, on the other hand, is memory-effective and perfect for sparse graphs, making it easier to traverse the graph and perform other operations. In computer science and other fields, both representations are used as essential data structures to address graph-related issues. These strategies can be used by programmers to create reliable algorithms and apps that function with intricate networks and interrelated data.

Updated on: 04-Aug-2023

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements