문제풀이
JS Map 객체를 사용한 풀이
const bfs = (graph, start, n) => {
let visit = new Array(n).fill(false);
let queue = [];
let arr = [];
visit.push(start);
queue.push([start, 0]);
while (queue.length > 0) {
const [node, cnt] = queue.shift();
const values = graph.get(node);
for (const value of values) {
if (!visit.includes(value)) {
visit.push(value);
queue.push([value, cnt + 1]);
arr.push(cnt + 1);
}
}
}
let max = Math.max(...arr);
let answer = 0;
for (const cnt of arr) {
if (max === cnt) answer++;
}
return answer;
}
function solution(n, edge) {
let graph = new Map();
for(let [a, b] of edge) {
graph.get(a)? graph.set(a, [...graph.get(a), b]) : graph.set(a, [b]);
graph.get(b)? graph.set(b, [...graph.get(b), a]) : graph.set(b, [a]);
}
return bfs(graph, 1, n);
}
JS Object를 사용한 풀이
const bfs = (graph, start, n) => {
let visit = new Array(n).fill(false);
let queue = [];
let arr = [];
visit.push(start);
queue.push([start, 0]);
while (queue.length > 0) {
const [node, cnt] = queue.shift();
for (const value of graph[node]) {
if (!visit.includes(value)) {
visit.push(value);
queue.push([value, cnt + 1]);
arr.push(cnt + 1);
}
}
}
let max = Math.max(...arr);
let answer = 0;
for (const cnt of arr) {
if (max === cnt) answer++;
}
return answer;
}
function solution(n, edge) {
let graph = {};
for (let [a, b] of edge) {
graph[a] ? graph[a].push(b) : graph[a] = [b];
graph[b] ? graph[b].push(a) : graph[b] = [a];
}
return bfs(graph, 1, n);
}