Graph
Graph
class Solution {
public:
// Function to return Breadth First Traversal of given graph.
vector<int> bfsOfGraph(int V, vector<int> adj[]) {
int vis[V] = {0};
vis[0] = 1;
queue<int> q;
// push the initial starting node
q.push(0);
vector<int> bfs;
// iterate till the queue is empty
while(!q.empty()) {
// get the topmost element in the queue
int node = q.front();
q.pop();
bfs.push_back(node);
// traverse for all its neighbours
for(auto it : adj[node]) {
// if the neighbour has previously not been visited,
// store in Q and mark as visited
if(!vis[it]) {
vis[it] = 1;
q.push(it);
}
}
}
return bfs;
}
};
[2]Simple DFS:
class Solution {
private:
void dfs(int node, vector<int> adj[], int vis[], vector<int>
&ls) {
vis[node] = 1;
ls.push_back(node);
// traverse all its neighbours
for(auto it : adj[node]) {
// if the neighbour is not visited
if(!vis[it]) {
dfs(it, adj, vis, ls);
}
}
}
class Solution {
private:
bool detect(int src, vector<int> adj[], int vis[]) {
vis[src] = 1;
// store <source node, parent node>
queue<pair<int,int>> q;
q.push({src, -1});
// traverse until queue is not empty
while(!q.empty()) {
int node = q.front().first;
int parent = q.front().second;
q.pop();
class Solution {
private:
bool dfsCheck(int node, vector<int> adj[], int vis[], int
pathVis[]) {
vis[node] = 1;
pathVis[node] = 1;
pathVis[node] = 0;
return false;
}
class Solution {
private:
bool dfs(int node, int col, int color[], vector<int> adj[]) {
color[node] = col;
return true;
}
[7] bipartite graph using bfs:
queue<int>q;
color[start]=0;
q.push(start);
while(!q.empty()){
int node=q.front();
q.pop();
for(auto nbr:adj[node]){
if(color[nbr]==-1){
color[nbr]=!color[node];
q.push(nbr);
}
else if(color[nbr]==color[node]){
return false;
}
}
}
return true;
}
class Solution {
private:
void dfs(int node, int vis[], stack<int> &st,
vector<int> adj[]) {
vis[node] = 1;
for (auto it : adj[node]) {
if (!vis[it]) dfs(it, vis, st, adj);
}
st.push(node);
}
class Solution {
public:
//Function to return list containing vertices in Topological
order.
vector<int> topoSort(int V, vector<int> adj[])
{
int indegree[V] = {0};
for (int i = 0; i < V; i++) {
for (auto it : adj[i]) {
indegree[it]++;
}
}
queue<int> q;
for (int i = 0; i < V; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
vector<int> topo;
while (!q.empty()) {
int node = q.front();
q.pop();
topo.push_back(node);
// node is in your topo sort
// so please remove it from the indegree
return topo;
}
};
[1] for a bipartite graph if nodes can be partitioned into two independent sets A and sets B such that
every edge in the graph connects a node A in set A and a node B in set B
To find shortest length we can’t find with normal dfs we have to use logic of directed graph cycle
detection otherwise go with bfs traversal with formula dist[node]+dist[nbr]+1;