-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path39.js
83 lines (77 loc) · 1.3 KB
/
39.js
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
/**
* 너비 우선 탐색 순회
* @param {number[][]} graph
* @param {number} start
* @returns {number[]}
*/
function solution(graph, start) {
// 그래프를 인접 리스트로 변환
const adjList = {};
for (let [u, v] of graph) {
if (!adjList[u]) adjList[u] = [];
adjList[u].push(v);
}
const visited = new Set();
const queue = new Queue();
queue.push(start);
visited.push(start);
const result = [start];
while (!queue.isEmpty()) {
const node = queue.pop();
for (const neighbor of adjList[node] || []) {
if (!visited.has(neighbor)) {
queue.push(neighbor);
visited.add(neighbor);
result.push(neighbor);
}
}
}
return result;
}
class Queue {
items = [];
front = 0;
rear = 0;
push(item) {
this.items.push(item);
this.rear++;
}
pop() {
return this.items[this.front++];
}
isEmpty() {
return this.front === this.rear;
}
}
const log = console.log;
log(
solution(
[
[1, 2],
[1, 3],
[2, 4],
[2, 5],
[3, 6],
[3, 7],
[4, 8],
[5, 8],
[5, 9],
[6, 9],
[7, 9],
],
1
)
); // [1,2,3,4,5,6,7,8,9]
log(
solution(
[
[0, 1],
[1, 2],
[2, 3],
[3, 4],
[4, 5],
[5, 0],
],
1
)
); // [1,2,3,4,5,0]