-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS.java
81 lines (67 loc) · 1.39 KB
/
DFS.java
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
79
80
81
/*
SAMPLE INPUT
10 9
0 1
0 2
1 5
1 6
2 3
2 4
6 7
6 8
8 9
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Solution {
static ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
static Boolean[] visited;
static int flag=0;
static int n=0;
static int m=0;
public static void main(String args[]){
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = in.nextInt();
visited = new Boolean[n];
for(int j=0;j<n;j++){
visited[j]=false;
}
int a;
int b;
for(int i=0;i<n;i++){
al.add(new ArrayList<Integer>());
}
for(int i=0;i<m;i++){
a= in.nextInt();
b= in.nextInt();
al.get(a).add(b);
al.get(b).add(a);
}
visit();
}
public static void dfs(int n)
{
visited[n]=true;
System.out.println("Visiting node: " + n);
for(Integer list:al.get(n))
{
if(al.get(n)!=null)
{
if(!visited[list]){
dfs(list);
}
}
}
}
public static void visit()
{
for(int i=0;i<n;i++)
{
if(!visited[n]){
dfs(n);
}
}
}
}