Graph representation


You can represent a graph in many ways.
Graph terminology:
 Vertices: From below graph 1, 2, 3, 4 are Vertices.
 Edges: (1,2), (2,3)..etc are edges.
 Degree: Number of edges from the vertex.
              From below graph  vertex 1 degree is 2 because it had two edges which are(1,2) (1,4).
  Order: Number of vertices will be graph order.
  Size: Number of Edges will be graph size.
Note: The Sum of the degrees is twice the number of edges.

Spanning subgraph: A graph obtained only by edge deletion(G\E).
(i.e Original graph and subgraph number of vertices should be same)

Induced subgraph: A graph obtained only by vertex deletion(G-V)

Edge Existence:

Source: https://www.hackerearth.com/
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
1Q103

The two most common ways of representing a graph is as follows:

Adjacency matrix:
It needs lot of space because if there is no edge between the vertices's it will store the value as zero.

The adjacency matrix of the following graph is:

i/j : 1 2 3 4
1 :   0 1 0 1
2 :   1 0 1 0
3 :   0 1 0 1
4 :   1 0 1 0


Note: If graph has some weight we can represent in the matrix with respective weight instead of 0's and 1's.

In real time scenarios this weight could be distance between two cities.
If you take network as example then  file transfer capacity between the two system could be the graph weight.

below code will illustrate the edge representation with adjacent matrix.



Adjacency list

  Adjacency list graph representation takes less memory compare to adjacency matrix because it will linked to the adjacent vertex.

    0       1          2       3
 [[1 2], [2 4], [3 1 4], [4 2]]

A 1 → 2
A 2 → 4
A 3 → 1 → 4
A 4 → 2


No comments:

Post a Comment