-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBOJ1260.js
63 lines (49 loc) · 1.38 KB
/
BOJ1260.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
// Solution 1
function solution(n, m, v, lines) {
const dfsGraph = [];
const bfsGraph = [];
const graph = Array.from({ length: n + 1 }, () => Array(n + 1).fill(0));
const dfsVisited = Array.from({ length: n + 1 }, () => false);
const bfsVisited = Array.from({ length: n + 1 }, () => false);
lines.forEach((line) => {
const [x, y] = line;
graph[x][y] = 1;
graph[y][x] = 1;
});
function dfs(v) {
dfsVisited[v] = true;
dfsGraph.push(v);
for (let i = 1; i <= n; i++) {
if (graph[v][i] === 1 && !dfsVisited[i]) {
dfs(i);
}
}
}
function bfs(v) {
const queue = [];
queue.push(v);
bfsGraph.push(v);
while (queue.length !== 0) {
const value = queue.shift();
bfsVisited[value] = true;
for (let i = 1; i <= n; i++) {
if (graph[value][i] === 1 && !bfsVisited[i]) {
bfsVisited[i] = true;
queue.push(i);
bfsGraph.push(i);
}
}
}
}
dfs(v);
bfs(v);
const results = [dfsGraph.join(' '), bfsGraph.join(' ')].join('\n');
return results;
}
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const [n, m, v] = input[0].split(' ').map((value) => parseInt(value));
const lines = input
.slice(1)
.map((row) => row.split(' ').map((value) => parseInt(value)));
console.log(solution(n, m, v, lines));