-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMain.java
76 lines (60 loc) Β· 2.01 KB
/
Main.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
package DFSandBFS.P1260;
import java.io.*;
import java.util.*;
public class Main {
static int N, M, V;
static LinkedList<Integer>[] graph;
static boolean[] visited;
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("src/DFSandBFS/P1260/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
V = Integer.parseInt(st.nextToken());
graph = new LinkedList[N];
for (int i = 0; i < N; i++) {
graph[i] = new LinkedList<>();
}
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int f = Integer.parseInt(st.nextToken()) - 1;
int t = Integer.parseInt(st.nextToken()) - 1;
graph[f].add(t);
graph[t].add(f);
}
for (int i = 0; i < N; i++) {
Collections.sort(graph[i]);
}
visited = new boolean[N];
dfs(V-1);
System.out.println("");
visited = new boolean[N];
bfs(V-1);
}
static void dfs(int start) {
visited[start] = true;
System.out.print(start + 1 + " ");
for (int i = 0; i < graph[start].size(); i++) {
int target = graph[start].get(i);
if (!visited[target])
dfs(target);
}
}
static void bfs(int start) {
Queue<Integer> q = new LinkedList<>();
visited[start] = true;
q.offer(start);
while (!q.isEmpty()) {
int target = q.poll();
System.out.print(target + 1 + " ");
for (int i = 0; i < graph[target].size(); i++) {
int next = graph[target].get(i);
if (!visited[next]) {
visited[next] = true;
q.offer(next);
}
}
}
}
}