diff --git a/Graph 1/BFS Traversal b/Graph 1/BFS Traversal index e25347b..bf6808b 100644 --- a/Graph 1/BFS Traversal +++ b/Graph 1/BFS Traversal @@ -5,103 +5,48 @@ E is the number of edges present in graph G. Note : 1. Take graph input in the adjacency matrix. 2. Handle for Disconnected Graphs as well - - #include -#include -#include -#include +#include +#include +#include using namespace std; - - -vector * getpath( int ** graph , int v , int s ,int e , bool * visited) -{ - queue pn; - unordered_map m; - pn.push(s); - visited[s]=true; - - while(!pn.empty()) - { - int t= pn.front(); - - pn.pop(); - - - for(int i=0 ; i * ans = new vector(); - - ans->push_back(e); - int x =e; - while(m[x]!=s) - { - ans->push_back(m[x]); - x=m[x]; - } - ans->push_back(s); - - return ans; - } - } - } - - -} - return NULL; -} - - -int main() -{ - int V, E; - cin >> V >> E; - - int** graph = new int * [V]; - for( int i=0 ;i>x>>y ; - graph[x][y]=1; - graph[y][x]=1; - } - bool * visited = new bool[V]; - for ( int i=0 ;i>s>>e; - - vector * ans = getpath(graph , V,s,e,visited); - if(ans) - { - for(int i=0 ;i< ans->size(); i++) - cout<< ans->at(i) << " "; +int main() { + // Write your code here + int v,e; + cin >> v >> e; + + vector> edges(v, vector(v, false)); + + for(int i = 0; i < e; ++i) { + int first; + int second; + cin >> first >> second; + edges[first][second] = true; + edges[second][first] = true; } - delete ans; + vector visited(v, false); -for(int i=0 ;i q; - delete [] visited; + // If the graph is a connected component graph + // We Call BFs for each Component + for(int i = 0; i < v ; i++) { + if(!visited[i]) { + q.push(i); + visited[i] = true; + while(!q.empty()) { + int front = q.front(); + q.pop(); + cout << front << " "; + + for(int i = 0; i < v; i++) { + if(edges[front][i] and !visited[i]) { + q.push(i); + visited[i] = true; + } + } + } + } + } - return 0; } diff --git a/binary trees/find a node b/binary trees/find a node index 0b29b70..24d18b7 100644 --- a/binary trees/find a node +++ b/binary trees/find a node @@ -2,23 +2,22 @@ Given a Binary Tree and an integer x, check if node with data x is present in th bool isNodePresent(BinaryTreeNode* root, int x) { - - - if(root->data==x) - ans =true; - - bool ans=false; - if(root->left) - { bool leftans= isNodePresent(root->left,x); - if(leftans) - ans=leftans; - } - - if(root->right) - { bool rightans= isNodePresent(root->right,x); - if(rightans) - ans=rightans; - } - return ans; + // Write your code here + if (root == NULL) + return false; + if (root->left != NULL) { + bool val = isNodePresent(root->left, x); + if (val == true) + return true; + } + if (root->right != NULL) { + bool val = isNodePresent(root->right, x); + if (val == true) + return true; + } + if (root->data == x) + return true; + else + return false; }