Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8981fa3

Browse files
Add dfs template
1 parent 6fc8ccc commit 8981fa3

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎dfs.cpp‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <bits/stdc++.h>
2+
#define ll long long
3+
using namespace std;
4+
5+
struct node {
6+
bool visited;
7+
vector<ll> adj;
8+
};
9+
10+
void explore(vector<node> &graph, ll u) {
11+
graph[u].visited = true;
12+
for(ll i=0; i<graph[u].adj.size(); i++) {
13+
ll v = graph[u].adj[i];
14+
if(!graph[v].visited) {
15+
explore(graph,v);
16+
}
17+
}
18+
}
19+
20+
void dfs(vector<node> &graph, ll n) {
21+
for(ll i=1; i<=n; i++) {
22+
if(!graph[i].visited) {
23+
explore(graph,i);
24+
}
25+
}
26+
}
27+
28+
int main() {
29+
ll n,e,i,s,u,v,d;
30+
cin>>n>>e;
31+
vector<node> graph(n+1);
32+
for(i=0;i<n;i++) {
33+
graph[i].visited = false;
34+
}
35+
for(i=0;i<e;i++) {
36+
cin>>u>>v;
37+
graph[u].adj.push_back(v);
38+
graph[v].adj.push_back(u);
39+
}
40+
dfs(graph,n);
41+
return 0;
42+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /