https://programmers.co.kr/learn/courses/30/lessons/43162
class Node {
constructor(index, children){
this.visit = false;
this.index = index;
this.children = children;
}
}
function solution(n, computers) {
const nodes = [];
computers.forEach((computer, index) => {
const children = [];
computer.forEach((child,i) => {
if (index !== i && child === 1) {
children.push(i);
}
});
nodes.push(new Node(index, children));
});
let networkCount = 0;
nodes.forEach(node => {
node.children.forEach(c => {
if (!nodes[c].visit) {
visit(nodes[c]);
networkCount++;
}
});
if (!node.visit && node.children.length === 0) {
networkCount++;
}
});
function visit(node) {
if (node.visit) {
return;
}
if (node.children.length === 0) {
return;
}
node.visit = true;
node.children.forEach(c => {
visit(nodes[c]);
});
}
return networkCount;
}
처음엔 Node class를 만들어서 풀었다.
visit와 children을 관리하기 위해서였다.
Node 대신에, visit을 관리하는 array를 만들어 아래와 같이 수정했다.
function solution(n, computers) {
let networkCount = 0;
const visit = Array.from({length : n}, () => false);
computers.forEach((computer, index) => {
computer.forEach((c,i) => {
if (c === 1) {
networkCount += dfs(i);
}
})
});
return networkCount;
function dfs(computer) {
if (visit[computer]) {
return 0;
} else {
visit[computer] = true;
}
computers[computer].forEach((c,i) => {
if (c === 1) {
dfs(i);
}
});
return 1;
}
}