Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
💭 그래프 탐색 2 — 최솟값 갱신을 위한 재방문 허용
이 문제는 최단 거리 또는 최소 비용을 구하는 문제로 판단하여, 그래프 탐색 알고리즘 중 다익스트라 알고리즘과 유사한 접근이 필요하다고 느꼈습니다.
처음에는 단순한 BFS로 접근했지만, 탐색 과정에서 이미 방문한 노드라도 더 적은 비용으로 다시 방문할 수 있는 상황이 발생할 수 있다는 점에서 일반적인 BFS와는 다른 전략이 필요했습니다.
왜 다익스트라 느낌?
간선마다 고정된 비용이 있고,
한 노드를 여러 번 방문할 수 있으며,
더 적은 비용으로 갱신될 가능성이 있다면 → 다익스트라처럼 우선순위 큐 혹은 비용 기반 정렬을 고려해야 합니다.
단순 방문 처리로는 오답이 되는 이유
처음에는 방문한 노드를 다시 탐색하지 않기 위해 visited 배열을 사용했지만, 이 방식은 오히려 최솟값 갱신이 필요한 경우를 놓치게 됩니다.
예를 들어,
노드 2에서 노드 1로 돌아가는 경로가 더 짧은 경우가 생길 수 있습니다.
이때 visited[1] == true로 인해 해당 경로를 무시하면, 최소 비용이 아닌 경로가 정답이 되어버립니다.
→ 정답 배열(ans[])만 사용하고, 방문 배열은 사용하지 않는 전략이 필요합니다.
그래서 선택한 전략 !
정답 배열을 Integer.MAX_VALUE로 초기화하여, 어떤 값이든 더 작으면 무조건 갱신될 수 있게 설계합니다.
이후 탐색 중 if (ans[next] > ans[cur] + cost) 조건을 만족하면, ans[next]를 갱신하고 큐에 넣어 재탐색을 허용합니다.
최종적으로 ans[i] == Integer.MAX_VALUE인 노드는 도달할 수 없는 노드이므로, 출력 시 -1로 바꿔 출력합니다.