-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.js
44 lines (44 loc) · 1.2 KB
/
solution.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
const filePath = require('path').join(__dirname, 'input');
const [num, ...arr] = require('fs')
.readFileSync(filePath)
.toString()
.trim()
.split('\n');
const [n, m] = num.split(' ').map(Number);
function solution(n, m, arr) {
const graph = Array.from({ length: n + 1 }, () => []);
for (let i = 0; i < m; i++) {
const [child, parent] = arr[i].split(' ');
graph[+parent].push(+child);
}
const dfs = (start) => {
const stack = [start];
const visited = new Array(n + 1).fill(0);
visited[start] = 1;
let count = 0;
while (stack.length) {
const node = stack.pop();
for (let v of graph[node]) {
if (visited[v]) continue;
visited[v] = 1;
stack.push(v);
count++;
}
}
return count;
}
let maxCount = 0;
let answer = [];
for (let i = 1; i <= n; i++) {
const count = dfs(i);
if (count > maxCount) {
answer = [];
maxCount = count
}
if (count === maxCount) {
answer.push(i);
}
}
return answer.join(' ');
}
console.log(solution(+n, +m, arr));