Vertices,edges,undirected and directed graph,cyclic & acyclic graph,degree indegree & outdegree and weights. In an undirected graph, the sum of degrees of all vertices is double the vertices (We consider degree=indegree=outdegree in an undirected graph).
Graph representation in C++
Let us say there are n nodes and m edges. And adj[i][j] represents there is an edge from node i to j.
There are two ways to represent a graph
1. Adjacency matrix:
Time Complexity:O(m)**** Space Complexity:**O(n*n)**
2. Adjacency List
Time Complexity:**O(m)** Space Complexity:**O(n*n)**
If there are also weights in edges, we create the adjacency list as ' vector <vector < pair <int,int> > > ' where first value is node(v) and second value represents weight b/w the nodes(u and v).
Since there can be multiple disconnected components in a graph, while graph traversal we have to call BFS/DFS from every unvisited node. To avoid repetition we store information if a node is visited or not by creating a boolean array where is_visited[i]==true represents node 'i' is visited.
for(int i=1i<=n;i++)
{
if(!is_visited[i]) BFS(i);
}
BFS
Time Complexity:**O(n+e)** ( O(n+e): n time taken for visiting n nodes and e time taken for traversing through adjacent nodes)
Space Complexity:**O(n)** ( O(n) for visiting array and O(n) for queue )
DFS
Time Complexity:**O(n+e)** ( O(n+e): n time taken for visiting n nodes and e time taken for traversing through adjacent nodes)
Space Complexity:**O(n)** ( O(n) for visiting array and O(n) for stack space )
Cycle Detection in Graphs
Case 1: Cycle detection in undirected graph using dfs
If a node adjacent to a node ( that is not its parent node ) is already visited, the component contains a cycle.
Case 2:Cycle detection in the undirected graph using BFS
Case 3:Cycle detection in the Directed graph using DFS-
Case 3:Cycle detection in the Directed graph using BFS
Assume the directed graph to be acyclic i.e. DAG and find its topological order.If we can do topological sorting i.e. pushing all nodes in queue , the graph is acyclic,other wise it is cyclic.
We increase our count by 1 (starting from 0) each time we push a node in queue. And if final value of count==no. of nodes in graph, the graph is a DAG.
Bipartite graph:
A graph will not be a bipartite iff it has a cycle with an odd no. of nodes.
Check whether a graph is bipartite or not using BFS
Check whether a graph is bipartite or not using DFS
Topological Sorting:
Only possible in DAG. It is a linear order of vertices such that for every directed edge u-->v, vertex u comes before v in that order. A DAG has at least one node with indegree=0.
Topological sorting using BFS
First, calculate indegree of all nodes and store it in vector.Then push all nodes with degree==0 in a queue.Take each node one by one out of queue and for all its child ,decrease their indegree by 1. After this if any child has indegree==0, push them in the queue.
Topological sorting using DFS
Topological order is the order of nodes in decreasing order of finishing time i.e. the node that gets finished at last comes first in order.
Shortest path algorithms:
Shortest path of all nodes from a node in a uni-weighted undirected graph.
Use BFS for this because BFS visits nodes in a sequential manner. That is nodes at the same level are visited simultaneously. Run BFS and equate dist[node] = 1+dist[parent].
Shortest path of all nodes from a node in a weighted DAG
The weights can be -ve.
Minimum sum to reach a node 'v' i.e. dist[v] is minimum of all (dist[u]+weight(u-->v)),where u is node from all its parents. Similarly, dist[u] is calculated with the help of its parents.We can observe that ultimately we have to start calculating dist[] from source node and in topological order ,we have to visit the nodes
We visit nodes in topological order and relax all its children. In this way, each node is relaxed by all its parents.
Shortest path in +ve weighted graph.
Dijkstra's algorithm is basically an efficient version of breadth-first search on a different graph.
Given a graph G with positive integer edge-weights, one could construct a new unweighted graph H, by replacing each weighted edge with a number of edges equivalent to its weight. So, for example, if you had an edge (u,v) with weight 10 in G, you'd replace this edge with a series of 10 edges between u and v.
Since BFS visits nodes in increasing order of their level (distance from source node) i.e. at any point of time,if a node n1 level is smaller than node n2, minimum distance from n1 will be calculated earlier than n2.
From this, we get an intuition that at any point of time, calculate minimum distance of children of that node which is nearest to the source node. This is a kind of greedy approach because we are relaxing children of that node which is locally(at a point of time) nearest to the source.
Since min_priority_queue always stores elements in increasing order,we will use it.
Why djikstra doesn't work with -ve weights:
If all weights are non-negative, adding an edge can never make a path shorter but this is not valid if edge weight is -ve. .Dry run a case to explain it further