-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1260.js
79 lines (66 loc) · 1.68 KB
/
1260.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
var readline = require("readline");
var r = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let input = [];
r.on("line", function (line) {
input.push(line);
}).on("close", function () {
main(input);
process.exit();
});
function main(input) {
const [N, M, V] = input.shift().split(' ').map(Number);
const edges = input.map(v => v.split(' ').map(Number));
const graph = [...Array(N + 1)].map(() => []);
edges.forEach(([from, to]) => {
graph[from].push(to);
graph[to].push(from);
});
graph.forEach((arr) => {
arr.sort((a, b) => b - a)
})
dfs(V, graph)
bfs(V, graph)
}
function dfs(start, graph) {
graph.forEach((arr) => {
arr.sort((a, b) => b - a)
})
const visited = [...Array(graph.length)].fill(0);
const queue = [];
const result = [];
queue.push(start);
while (queue.length) {
let node = queue.pop();
if (!visited[node]) {
visited[node] = 1;
result.push(node);
graph[node].forEach((val) => {
queue.push(val);
})
}
}
console.log(result.join(' '))
}
function bfs(start, graph) {
graph.forEach((arr) => {
arr.sort((a, b) => a - b)
})
const visited = [...Array(graph.length)].fill(0);
const queue = [];
const result = [];
queue.push(start);
while (queue.length) {
let node = queue.shift();
if (!visited[node]) {
visited[node] = 1;
result.push(node);
graph[node].forEach((val) => {
queue.push(val);
})
}
}
console.log(result.join(' '))
}