File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[][]} richer
3+ * @param {number[]} quiet
4+ * @return {number[]}
5+ */
6+
7+ // 인접리스트 + dfs + 메모이제이션
8+ var loudAndRich = function(richer, quiet) {
9+ const n = quiet.length;
10+
11+ // graph[x]: x보다 직접적으로 부자인 사람들
12+ const graph = Array.from({ length: n }, () => []);
13+
14+ for (let i = 0; i < richer.length; i++) {
15+ const rich = richer[i][0];
16+ const poor = richer[i][1];
17+
18+ graph[poor].push(rich);
19+ }
20+
21+ // -1이면 아직 정답을 구하지 않았다는 뜻
22+ const answer = new Array(n).fill(-1);
23+
24+ function dfs(person) {
25+ // 이미 계산한 사람이라면 다시 계산하지 않음
26+ if (answer[person] !== -1) {
27+ return answer[person];
28+ }
29+
30+ // 처음에는 자기 자신이 가장 조용하다고 가정
31+ answer[person] = person;
32+
33+ // 현재 사람보다 부자인 사람들을 탐색
34+ for (const richPerson of graph[person]) {
35+ const candidate = dfs(richPerson);
36+
37+ // candidate가 현재 정답보다 더 조용한 경우
38+ if (quiet[candidate] < quiet[answer[person]]) {
39+ answer[person] = candidate;
40+ }
41+ }
42+
43+ return answer[person];
44+ }
45+
46+ // 모든 사람의 정답 구하기
47+ for (let i = 0; i < n; i++) {
48+ dfs(i);
49+ }
50+
51+ return answer;
52+ };
You can’t perform that action at this time.
0 commit comments