hwooo
프로그래머스 (C/C++) 49189 : 가장 먼 노드 본문
https://school.programmers.co.kr/learn/courses/30/lessons/49189
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr

풀이
BFS로 탐색하여 1번 노드와 가까운 노드부터 순차적으로 탐색.
가장 먼 거리를 maxLev, 해당 거리의 노드의 개수를 maxLevCnt로 저장 후 maxLev과 같은 거리의 노드 개수를 구함
코드
#include <string>
#include <vector>
#include <queue>
using namespace std;
int solution(int n, vector<vector<int>> edge) {
vector<int> graph[20001];
// connect nodes
for (auto e : edge) {
graph[e[0]].push_back(e[1]);
graph[e[1]].push_back(e[0]);
}
int maxLev = 0, maxLevCnt = 1;
bool visited[20001];
queue<pair<int, int>> q;
q.push({1, 1});
visited[1] = true;
while (!q.empty()) {
int now = q.front().first, nowLev = q.front().second;
q.pop();
// update maxLev Info
if (nowLev > maxLev) {
maxLev = nowLev;
maxLevCnt = 1;
}
else if (nowLev == maxLev)
maxLevCnt++;
for (int next : graph[now]) {
if (visited[next]) continue;
q.push({next, nowLev + 1});
visited[next] = true;
}
}
return maxLevCnt;
}
'Study > Algorithm' 카테고리의 다른 글
| LeetCode (C/C++) 456. 132 Pattern (0) | 2024.10.16 |
|---|---|
| LeetCode (C/C++) 164. Maximum Gap (0) | 2024.10.16 |
| LeetCode (C/C++) 2352. Equal Row and Column Pairs (0) | 2024.10.15 |
| LeetCode (C/C++) 1277. Count Square Submatrices with All Ones (0) | 2024.10.15 |
| 프로그래머스 (C/C++) 258712 : 가장 많이 받은 선물 (0) | 2024.06.14 |