BFS나 DFS나 결국 모든 노드를 도는 건 똑같은데 왜 BFS로는 풀리고 DFS로는 안풀릴까요?
처음에 DFS로 구현했다가 BFS로 바꾸니까 통과되네요.
알고리즘은 다 똑같고 stack 이용시에는 unshift를 이용해 요소를 추가했고 queue 이용시에는 push를 이용해 요소를 추가했습니다.
요소를 빼는건 shift로 모두 동일하게 사용했습니다.
아래 코드는 unshift 대신 push, shift 대신 pop을 이용했습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 function solution(n, edges) { const connectedList = getConnectedList(n, edges); const isVistied = new Array(n + 1).fill(false); const minDistance = new Array(n + 1).fill(Number.MAX_SAFE_INTEGER); const queue = new Array(); queue.push(1); minDistance[0] = 0; minDistance[1] = 0; isVistied[1] = true; while (queue.length) { const from = queue.pop(); connectedList[from].forEach((to) => { if (!isVistied[to]) { queue.push(to); isVistied[to] = true; } minDistance[to] = minDistance[to] > minDistance[from] + 1 ? minDistance[from] + 1 : minDistance[to]; }); } const max = Math.max(...minDistance); const answer = minDistance.filter((d) => d === max); return answer.length; } function getConnectedList(n, edges) { const connectedList = new Array(n + 1).fill(0).map((x) => new Array(0)); edges.forEach((edge) => { connectedList[edge[0]].push(edge[1]); connectedList[edge[1]].push(edge[0]); }); return connectedList; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
function solution(n, edges) { const connectedList = getConnectedList(n, edges); const isVistied = new Array(n + 1).fill(false); const minDistance = new Array(n + 1).fill(Number.MAX_SAFE_INTEGER); const queue = new Array(); queue.push(1); minDistance[0] = 0; minDistance[1] = 0; isVistied[1] = true; while (queue.length) { const from = queue.pop(); connectedList[from].forEach((to) => { if (!isVistied[to]) { queue.push(to); isVistied[to] = true; } minDistance[to] = minDistance[to] > minDistance[from] + 1 ? minDistance[from] + 1 : minDistance[to]; }); } const max = Math.max(...minDistance); const answer = minDistance.filter((d) => d === max); return answer.length; } function getConnectedList(n, edges) { const connectedList = new Array(n + 1).fill(0).map((x) => new Array(0)); edges.forEach((edge) => { connectedList[edge[0]].push(edge[1]); connectedList[edge[1]].push(edge[0]); }); return connectedList; }
음.. 100% 안된다고는 장담할 수 없지만 아시다시피 DFS의 경우 깊이가 깊어지는 간선을 먼저 탐색하기 때문에, (1, 2) , (1, 3), (2, 3) 이렇게 연결되있을 때 3번 노드는 1번 노드로부터 1의 깊이를 가지지만 DFS로 탐색할 경우 1->2->3 순으로 탐색하기 때문에 3번 노드가 1번 노드로부터 2의 깊이를 가지게 되서 모순이 발생할 거 같네요.