첫 번째 시도 : 7,8,9 core dumped error

function solution(n, edge) {
var answer = 0;
const visited = Array(n).fill(0);
const graph = visited.map((row) => Array(n).fill(0));
edge.forEach((e, i) => {
const [start, end] = e;
graph[start - 1][end - 1] = 1;
graph[end - 1][start - 1] = 1;
});
const queue = [[0, 0]];
visited[0] = 1;
let ans = 0;
let max = 0;
while (queue.length) {
let [vertex, depth] = queue.shift();
const adjacencyList = graph[vertex];
adjacencyList.forEach((neighbor, i) => {
if (neighbor && !visited[i]) {
queue.push([i, depth + 1]);
visited[i] = 1;
if (max < depth + 1) {
max = depth + 1;
ans = 1;
} else {
ans++;
}
}
});
}
return ans;
}
통과된 풀이

function solution(n, edge) {
var answer = 0;
const visited = Array(n).fill(0);
const graph = Array(n)
.fill(0)
.map((row) => []);
edge.forEach((e, i) => {
const [start, end] = e;
graph[start - 1].push(end - 1);
graph[end - 1].push(start - 1);
});
const queue = [[0, 0]]; // 시작 포인트
visited[0] = 1;
let ans = 0;
let max = 0;
while (queue.length) {
let [vertex, depth] = queue.shift();
const adjacencyList = graph[vertex];
adjacencyList.forEach((neighbor) => {
if (!visited[neighbor]) {
queue.push([neighbor, depth + 1]);
visited[neighbor] = 1;
if (max < depth + 1) {
max = depth + 1;
ans = 1;
} else {
ans++;
}
}
});
}
return ans;
}