-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPracticeDfs.java
More file actions
94 lines (68 loc) · 2.03 KB
/
PracticeDfs.java
File metadata and controls
94 lines (68 loc) · 2.03 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package PracticeGraphs;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class PracticeDfs {
ArrayList<ArrayList<Integer>> adj;
public PracticeDfs(int n ){
adj = new ArrayList<>();
for(int i = 0; i <= n; i++){
adj.add(new ArrayList<>());
}
}
public void addEdge(int src , int dest){
adj.get(src).add(dest);
}
public void dfs(int node, ArrayList<ArrayList<Integer>> adj , boolean vis[],ArrayList<Integer> ans){
vis[node] = true;
ans.add(node);
for(int it : adj.get(node)){
if(!vis[it]){
dfs(it, adj, vis,ans);
}
}
}
public void bfs(ArrayList<ArrayList<Integer>> adj , boolean vis[]){
Queue<Integer> q = new LinkedList<>();
q.offer(1);
vis[1] = true;
while(!q.isEmpty()){
int node = q.poll();
System.out.println(node);
for(int it :adj.get(node)){
if(!vis[it]){
vis[it] = true;
q.offer(it);
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
PracticeDfs p = new PracticeDfs(n);
for(int i = 0; i < m; i++){
int src = sc.nextInt();
int dest = sc.nextInt();
p.addEdge(src - 1, dest - 1);
}
boolean vis[] = new boolean[n + 1];
ArrayList<Integer> ans = new ArrayList<>();
for(int i = 1; i <= n; i++){
if(!vis[i]){
p.dfs(i , p.adj , vis,ans);
}
}
for(int i = 0; i < ans.size(); i++){
System.out.println(ans.get(i));
}
vis = new boolean[n + 1];
for(int i = 1; i <= n; i++){
if(!vis[i]){
p.bfs(p.adj , vis);
}
}
}
}