-
[못풀었다/프로그래머스] 가장 먼 노드코딩테스트 2023. 6. 10. 13:54
function solution(n, edge) { var answer = 0; const graph = Array.from({length:n+1},()=>[]) for(let i=0;i<edge.length;i++){ graph[edge[i][0]].push(edge[i][1]) graph[edge[i][1]].push(edge[i][0]) } const visited = Array.from({length:n+1},()=>false) const distance = Array.from({length:n+1},()=>0) bfs(graph,visited,distance) let max = Math.max(...distance) return distance.filter((el)=>el===max).length return answer; } function bfs(graph,visited,distance){ const queue = [1]; visited[1] = true; while(queue.length){ let node = queue.shift(); graph[node].forEach((nodes)=>{ if(!visited[nodes]){ queue.push(nodes) visited[nodes] = true; distance[nodes] = distance[node]+1; } }) } }
bfs로 풀어야겠다는 생각까지는 했는데 distance를 어떻게 처리해야할지 막막했다.
현재 노드의 distance에 +1을 하면 다음 노드의 distance가 된다!
'코딩테스트' 카테고리의 다른 글
[릿코드] 228. Summary Ranges (0) 2023.06.14 [못풂/꼭 다시풀기/프로그래머스] 섬 연결하기 (0) 2023.06.10 [릿코드/문제잘보기] 744. Find Smallest Letter Greater Than Target (0) 2023.06.09 [다시풀기/프로그래머스] 이분탐색 (0) 2023.06.09 [못풀었다/프로그래머스] 불량사용자 (0) 2023.06.09