-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphListList.java
More file actions
77 lines (71 loc) · 1.15 KB
/
GraphListList.java
File metadata and controls
77 lines (71 loc) · 1.15 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
package algorithm;
import java.util.*;
public class GraphListList {
static int N;
static List<Integer>[] g;
static boolean[] v;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
int E = sc.nextInt();
g = new List[N];
for (int i = 0; i < N; i++)
g[i] = new ArrayList<>();
v = new boolean[N];
for (int i = 0; i < E; i++) {
int from = sc.nextInt();
int toto = sc.nextInt();
g[from].add(toto);
g[toto].add(from);
}
for (List<Integer> a : g)
System.out.println(a);
System.out.println();
bfs(0);
// dfs(0);
sc.close();
}
static void bfs(int i) {
ArrayDeque<Integer> q = new ArrayDeque<>();
v[i] = true;
q.offer(i);
while (!q.isEmpty()) {
i = q.poll();
System.out.print((char) (i + 'A') + " ");
for (int j : g[i]) {
if (!v[j]) {
v[j] = true;
q.offer(j);
}
}
}
}
static void dfs(int i) {
v[i] = true;
System.out.print((char) (i + 'A') + " ");
for (int j : g[i]) {
if (!v[j])
dfs(j);
}
}
}
/*
* 7
* 8
* 0 1
* 0 2
* 1 3
* 1 4
* 2 4
* 3 5
* 4 5
* 5 6
*
* A0
* / \
* B1 C2
* / \ /
* D3 E4
* \ /
* F5 - G6
*/