Friday, 7 July 2017

Graph Theory

Graph Theory

Adjacency matrix
An adjacency matrix is a VxV binary matrix A. Element Ai,j is 1 if there is an edge from vertex i to vertex j else Ai,j is 0.
Note: A binary matrix is a matrix in which the cells can have only one of two possible values - either a 0 or 1.
The adjacency matrix can also be modified for the weighted graph in which instead of storing 0 or 1 in Ai,j, the weight or cost of the edge will be stored.
In an undirected graph, if Ai,j = 1, then Aj,i = 1. In a directed graph, if Ai,j = 1, then Aj,i may or may not be 1.
Adjacency matrix provides constant time access (O(1) ) to determine if there is an edge between two nodes. Space complexity of the adjacency matrix is O(V2).
The adjacency matrix of the following graph is:

i/j1 2 3 4
1 : 0 1 0 0
2 : 0 0 0 1
3 : 1 0 0 1
4 : 0 1 0 0
enter image description here


code for adjacency matrix

#include<iostream>
using namespace std;
int main(){

    int x,y,node,edge;

    cin>>node>>edge;

    int a[10][10]={0};

    for(int i=0;i<edge;i++){

        cin>>x>>y;

        a[x][y]=1;
        
    }
  
}

TEST YOUR UNDERSTANDING
Edge Existence
You have been given an undirected graph consisting of N nodes and M edges. This graph can consist of self-loops as well as multiple edges. In addition , you have also been given Q queries. For each query , you shall be given 2 integers A and B. You just need to find if there exists an edge between node A and node B. If yes, print "YES" (without quotes) else , print "NO"(without quotes).
Input Format:
The first line consist of 2 integers N and M denoting the number of nodes and edges respectively. Each of the next M lines consist of 2 integers A and B denoting an undirected edge between node A and B. The next line contains a single integer Q denoting the number of queries. The next Line contains 2 integers A and B denoting the details of the query.
Output Format
Print Q lines, the answer to each query on a new line.
Constraints:
1N103
1M103
1A,BN
#include<iostream>
using namespace std;
int main(){

    int x,y,node,edge;

    cin>>node>>edge;

    int a[10][10]={0};

    for(int i=0;i<edge;i++){

        cin>>x>>y;

        a[x][y]=1;
        
    }
  int r,p,q;
  cin>>r;
  for(int i=0;i<r;i++){
      cin>>p>>q;
      if(a[p][q]==1){
          cout<<"YES"<<endl;
          
      }
      else cout<<"NO"<<endl;
      
  }

}

No comments:

Post a Comment

Dynamic programming problem

Given a binary matrix, find out the maximum size square sub-matrix with all 1s. For example, consider the below binary matrix. Please...