Depth First Search - DFS


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<bits/stdc++.h>
using namespace std;

vector<int>adj[100];
bool visited[1000];

void DFS(int s)
{
    if(visited[s])
        return;
    cout<<s<<" ";
    visited[s]=true;

    for(int i=0;i<adj[s].size();i++)
        DFS(adj[s][i]);
}

int main()
{
    int n,e,a,b;
    cin>>n>>e;

    while(e--){
        cin>>a>>b;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }

    DFS(0);

    return 0;
}

/*
5 6
0 1
0 2
1 4
1 3
2 4
3 4
*/

No comments

Theme images by Jason Morrow. Powered by Blogger.