-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdfs_recursion
More file actions
78 lines (59 loc) · 1.53 KB
/
Copy pathdfs_recursion
File metadata and controls
78 lines (59 loc) · 1.53 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class graph {
int n,e;
HashMap<Integer,ArrayList<Integer>> list = new HashMap();
boolean v[];
//Constructor takes input
graph(){
n = i(); //no of nodes
e = i(); //no of egdes
for(int i=0;i<e;i++) //creating adjacency list
{
int a = i();
int b = i();
if(!list.containsKey(a))
list.put(a,new ArrayList());
if(!list.containsKey(b))
list.put(b,new ArrayList());
list.get(a).add(b);
list.get(b).add(a);
}
v = new boolean[n+1];
}
public void dfs(int root)
{
v[root] = true;
ArrayList<Integer> ar = list.get(root);
for(int i=0;i<ar.size();i++)
{
int node = ar.get(i);
if(!v[node]) // if element is not visited
{
dfs(node);
}
}
}
void p()
{
System.out.print();
}
public static void main(String[] args) {
graph g = new graph();
int root = 1;
g.dfs(root);
}
static Scanner sc = new Scanner(System.in);
static long l(){
return sc.nextLong();
}
static int i(){
return sc.nextInt();
}
static String s(){
return sc.nextLine();
}
}