- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Represent Graph Using Incidence Matrix
The incidence matrix of a graph is another representation of a graph to store into the memory. This matrix is not a square matrix. The order of the incidence matrix is V x E. Where V is the number of vertices and E is the number of edges in the graph.
In each row of this matrix we are placing the vertices, and in each column the edges are placed. In this representation for an edge e {u, v}, it will be marked by 1 for the place u and v of column e.
The complexity of Adjacency Matrix representation
The incidence matrix representation takes O(Vx E) amount of space while it is computed. For complete graph the number of edges will be V(V-1)/2. So incidence matrix takes larger space in memory.
Input
Output
E0 | E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8 | |
---|---|---|---|---|---|---|---|---|---|
0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
1 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 |
2 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 0 |
3 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 0 |
4 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
5 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 1 |
Algorithm
add_edge(u, v)
Input − The u and v of an edge {u,v}
Output − Incidence matrix of the graph G
At first, there are edge count ed_cnt is 0 for the incidence matrix.
Begin ed_cnt := ed_cnt + 1 inc_matrix[u, ed_cnt] := 1 inc_matrix[v, ed_cnt] := 1 End
Example Code (C++)
#include<iostream> using namespace std; int inc_arr[20][20]; //initial array to hold incidence matrix int ed_no = 0; void displayMatrix(int v, int e) { int i, j; for(i = 0; i < v; i++) { for(j = 0; j < e; j++) { cout << inc_arr[i][j] << " "; } cout << endl; } } void add_edge(int u, int v) { //function to add edge into the matrix with edge number inc_arr[u][ed_no] = 1; inc_arr[v][ed_no] = 1; ed_no++; //increase the edge number } main(int argc, char* argv[]) { int v = 6; //there are 6 vertices in the graph int e = 9; //there are 9 edges in the graph add_edge(0, 4); add_edge(0, 3); add_edge(1, 2); add_edge(1, 4); add_edge(1, 5); add_edge(2, 3); add_edge(2, 5); add_edge(5, 3); add_edge(5, 4); displayMatrix(v, e); }
Output
1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 0 0 1 1 0 0 0 1 0 0 0 1 0 1 0 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 1 1
To Continue Learning Please Login
Login with Google