-
Notifications
You must be signed in to change notification settings - Fork 13
백준11437번LCA #77
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
The head ref may contain hidden characters: "\uBC31\uC90011437\uBC88LCA"
백준11437번LCA #77
Conversation
단번에 이해되는 코드 설명이에요😀 |
이 친구 많이 고독해보이는데 얼른 성불시켜주세요😥 |
제가 공통 조상 알고리즘을 잘 몰라서 찾아봤는데 트리 형식으로 구현하는 건가 보네요. 그럼 bfs 말고 dfs 나 재귀를 이용해서 풀어보시는 게 어떨까요? bfs 는 너비우선탐색이기에 트리 레벨 순회를 할 수 밖에 없어 값이 커지거나 방문하지 않아도 될 노드를 찍을 수 밖에 없다고 생각합니다. 반면 stack을 이용한 dfs 나 재귀를 이용한 dfs 를 사용하여 원하는 노드까지 찍었다면 조상 노드로 다시 돌아가거나 하는 방법으로 풀어보시면 좋을 듯 합니다. |
// BFS구현 | ||
private static void BFS(int node) { | ||
Queue<Integer> queue = new LinkedList<Integer>(); | ||
queue.add(node); | ||
visited[node] = true; | ||
int level = 1; | ||
int now_size = 1; | ||
int count = 0; | ||
while (!queue.isEmpty()) { | ||
int now_node = queue.poll(); | ||
for (int next : tree[now_node]) { | ||
if (!visited[next]) { | ||
visited[next] = true; | ||
queue.add(next); | ||
parent[next] = now_node; // 부모 노드 저장 | ||
depth[next] = level; // 노드 depth 저장 | ||
} | ||
} | ||
count++; | ||
if (count == now_size) { | ||
count = 0; | ||
now_size = queue.size(); | ||
level++; | ||
} | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@j2woo
저도 방금전에 이 문제를 풀어보았는데요!
모든 노드의 depth를 구하기 위해 완전 탐색을 진행해야 하는 상황입니다.
너비 우선 탐색을 통해 depth(Level)를 구할 수도 있겠지만,
Level에 따라 깊게 들어가는 깊이 우선 탐색을 사용하는 것이 목적에 맞아 값을 구하기 수월할 것으로 생각이 됩니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
한 수 배워갑니다:)
📖 풀이한 문제
💡 문제에서 사용된 알고리즘
📜 코드 설명