Skip to content
This repository was archived by the owner on Jun 26, 2022. It is now read-only.

added DFS.cpp #838

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions cpp/BFS.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
const unsigned int M = 1000000007;
using namespace std;
// Check
using namespace __gnu_pbds;
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> T_set; // PBDS_set
typedef tree<int,null_type,less_equal<int>,rb_tree_tag,tree_order_statistics_node_update> T_multiset; // PBDS_multiset

void solve()
{
int n ,m,u,v;
cin>>n>>m;
vector<list<int>> adj(n+1);
vector<bool> vis(n+1,false);
for(int i = 0; i < n ; i++ ){
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
queue<int> temp;
temp.push(1);
vis[1] = true;
while(!temp.empty()){
int curr = temp.front();
cout<<curr<<" ";
temp.pop();
for(int elem : adj[curr]){
if(!vis[elem]){
temp.push(elem);
vis[elem] = true;
}
}
}

}
int main()
{
ios_base::sync_with_stdio(false);
cout.tie(NULL);
cin.tie(NULL);
solve();
return 0;
}
56 changes: 56 additions & 0 deletions cpp/DFS.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include<bits/stdc++.h>
using namespace std;
#define MAXSIZE 1000000

vector<vector<int> > graph(MAXSIZE);
bool vis[MAXSIZE];


void dfs(int start)
{
stack<int> s;
cout<<start<<" ";
vis[start]=true;
s.push(start);
while(!s.empty())
{
int first=s.top();
for(int i=0;i<graph[first].size();i++)
{
if(!vis[graph[first][i]])
{
cout<<graph[first][i]<<" ";
vis[graph[first][i]]=true;
s.push(graph[first][i]);
first=graph[first][i];
i=-1;
}
}
s.pop();
}
}
int main()
{

int n,u,v;
cin>>n;
for(int i=0;i<n-1;i++)
{
cin>>u>>v;
graph[u].push_back(v);
graph[v].push_back(u);
}

//to check adjacency list
// for(int i=1;i<=n;i++)
// {
// cout<<i<<"-> ";
// for(int j=0;j<graph[i].size();j++)
// cout<<graph[i][j]<<" ";
// cout<<endl;
// }

//dfs code
dfs(1);
return 0;
}