-
[프로그래머스] 가장 먼 노드알고리즘/프로그래머스 2021. 8. 16. 15:20
풀이
bfs를 이용하면 방문하는 노드가 최단거리가 됩니다. 거리를 기록하는 배열인 dist를 이용해 지금 노드에서 다음 노드를 방문할 때 +1을 해서 값을 갱신합니다.
코드
#include <string> #include <vector> #include <queue> using namespace std; int solution(int n, vector<vector<int>> edge) { int answer = 0; vector<vector<int>> vec(n + 1, vector<int>(n + 1)); size_t size = edge.size(); for (int i = 0; i < size; ++i) { auto n1 = edge[i][0]; auto n2 = edge[i][1]; vec[n1][n2] = 1; vec[n2][n1] = 1; } vector<bool> visited(n + 1, false); vector<int> dist(n + 1, 0); visited[1] = true; queue<int> q; q.push(1); while (!q.empty()) { auto node = q.front(); q.pop(); for (int i = 1; i <= n; ++i) { if (vec[node][i] == 1 && visited[i] == false) { visited[i] = true; q.push(i); dist[i] = dist[node] + 1; } } } int max = 0; for (int i = 1; i <= n; ++i) max = max < dist[i] ? dist[i] : max; for (int i = 1; i <= n; ++i) if (max == dist[i]) ++answer; return answer; }
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 디스크 컨트롤러 (0) 2021.09.15 [프로그래머스] N으로 표현 (0) 2021.08.17 [프로그래머스] 추석 트래픽 (0) 2021.08.15 [프로그래머스] 예상 대진표 (0) 2021.08.05 [프로그래머스] 올바른 괄호 (0) 2021.08.05