delete and search edge in adjacency matrix of a graph

Solutions on MaxInterview for delete and search edge in adjacency matrix of a graph by the best coders in the world

showing results for - "delete and search edge in adjacency matrix of a graph"
Brie
25 Nov 2018
1/*adjacency matrix implementation of directed graph:
2 0---->1---|
3 |         |---->4
4 |-> 2-->3-|*/
5#include <iostream>
6
7using namespace std;
8#define v 5
9void inti(int mat[][v])
10{
11    for(int i=0;i<v;i++)
12    {
13        for(int j=0;j<v;j++)
14        {
15            mat[i][j]=0;
16        }
17    }
18}
19void addedge(int mat[][v],int start,int endvertix)
20{
21    mat[start][endvertix]=1;
22}
23void check(int mat[][v],int start,int endvertix)
24{
25    if(mat[start][endvertix]==1)
26    {
27        cout<<"edge exists:"<<endl;
28    }
29    else
30    {
31        cout<<"edge does not exist:"<<endl;
32    }
33
34}
35void removeedge(int mat[][v],int start,int edgeend)
36{
37    mat[start][edgeend]=0;
38}
39void printmat(int mat[][v])
40{
41    for(int i=0;i<v;i++)
42    {
43        for(int j=0;j<v;j++)
44        {
45            cout<<mat[i][j]<<" ";
46        }
47        cout<<endl;
48
49    }
50}
51
52int main()
53{
54    int array_in_graph[v][v];
55    inti(array_in_graph);
56    addedge(array_in_graph,0,1);
57    addedge(array_in_graph,0,2);
58    addedge(array_in_graph,0,3);
59    addedge(array_in_graph,1,3);
60    addedge(array_in_graph,1,4);
61    addedge(array_in_graph,2,3);
62    addedge(array_in_graph,3,4);
63    printmat(array_in_graph);
64    cout<<"now above graph is not consider as we will remove edge '3->4' AND edge '1->3':"<<endl;
65    removeedge(array_in_graph,3,4);
66    removeedge(array_in_graph,1,3);
67    printmat(array_in_graph);
68    check(array_in_graph,1,4);
69    check(array_in_graph,3,4);
70    return 0;
71}
72