[프로그래머스] 네트워크
const dfs = (stack, computers, visited) => {
if (!stack.length) return
const nowVisit = stack.pop()
for (let [targetComputer, isLinked] of computers[nowVisit].entries()) {
if (isLinked) {
if (!visited[targetComputer]) {
visited[targetComputer] = true
stack.push(targetComputer)
}
}
}
dfs(stack, computers, visited)
}
const solution = (n, computers) => {
const visited = new Array(computers.length).fill(false)
let networkCount = 0
while (visited.includes(false)) {
const nowVisit = visited.findIndex((v) => v === false)
if (nowVisit != undefined) {
visited[nowVisit] = true
dfs([nowVisit], computers, visited)
networkCount++
}
}
return networkCount
}