Graph Representation
Wewill look at 2 types of graph representation techniques
1. Adjacency Matrix
2. Adjacency List
8.
Problems with AdjacencyMatrix Method
1. Space Requirements
This is easy technique but has O(n2
)space complexity
If n=105
then space required will be = (105
)2
= 1010
4 x 1010
Byte = 4x107
KB = 4x104
=40GB
2. BFS or DFS traversal is of order O(n2
) which is too slow
3. Adding a new node is not easy
Adjacency List: Implementation
No. of nodes : N
No of edges : M
Vector<int> array[N+1];
While(M--)
{
cin>>a>>b;
Array[a].push_back(b);
Array[b].push_back(a)
}
11.
Depth First Search
Each node can be assigned a
level, for e.g Node 1 can be
assigned level 0
Node 2 is only node at level 1
In DFS each level is traversed
then it goes to another level
How to do it? You visit a node
and mark it 1 from 0 in visited
array, to show its visited using
adjacency list.
We use stacks for operation
13.
We mark 1as 1 in visited array and check nodes connected to node 1, we see too and it shows
That it is not visited in visited arrya
14.
So now weadd 2 to the stack and 1 will be in pause state at the moment
15.
We reach node3 and mark it visited add it to stack and see if its connected nodes i.e. 2 is
Visited or not, so we find it is visited, and has no more nodes so we pop it out from stack, and
Process the top node now, which will be node 2 and checks another node, which is 4
18.
Now node 4was put in stack, and checked its connected node, which is 2, and is already visited, so
It goes to next node 5, which is not visited, so it adds 5 to stack and check its connected nodes, which
We see is node 4, and shows its visited, so node 5 will be poped out and node 4’s next connection 6
Will be taken into consideration.
20.
Node 6 hasnode 4 which is already visited, so 6 will pop out, then 4 will pop out as the pointer at 6
Shows no other element exists at 4, so it will pop out 4, then 2 then 1 and all nodes would have
Been traversed by now
Connected Components
Connected componentis a set of vertices such
that if you choose any two nodes from the set of
Vertices then there exists path between the two.
By definition a single node itself is a connected
Component. Hence the graph contains three
Connected components.
23.
Strongly connected components
Herewe have directed graph, where
We have 3 strongly connected components.
Strongly connected components are components
Where when you chose two, there exists a path
Between them (in directed graphs).
Choosing any two blue nodes will have a path
Back to it, but red to blue will not have blue to red
Path or blue to yellow will not have reverse path.
If we assume that graph is not directed, so it becomes
One weakly connected component of a directed graph.
24.
Counting number ofConnected
Components in undirected graphs
We have two CC, using dfs call to
any of the node, the whole cc will
Be traversed.
We will can iterate from one node
and iterate count, so in the end we
will have two cc