Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- JUnit 5
- 유니온 파인드
- 플로이드-와샬
- Effective Java
- 구현
- 프로그래머스
- dfs
- Kotlin
- mst
- 백준
- 에라토스테네스의 체
- java
- swea
- 위상정렬
- 그리디
- 동적계획법
- 시뮬레이션
- 수학
- 후니의 쉽게 쓴 시스코 네트워킹
- 세그먼트 트리
- Network
- 투 포인터
- CS
- 이분탐색
- BFS
- 백트래킹
- 스택
- 문자열
- 완전탐색
- 알고리즘
Archives
반갑습니다!
[프로그래머스] 가장 먼 노드 본문
풀이
BFS를 통해 1번 노드부터 모든점들을 방문하고 가장 오래 걸린 노드들의 개수를 출력해주면 된다. 초기 입력 값으로 들어오는 edge 배열을 인접 리스트로 변환하여 풀이하였다.
코드
#include <string>
#include <vector>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;
vector<vector<int>> adj;
vector<int> visited;
int bfs(){
queue<int> q;
q.push(1);
visited[1] = 0;
int ret = 0;
while(!q.empty()){
int cur = q.front();
q.pop();
for(int i=0; i<adj[cur].size(); i++){
int next = adj[cur][i];
if(visited[next] == -1){
visited[next] = visited[cur] + 1;
ret = max(ret, visited[next]);
q.push(next);
}
}
}
return ret;
}
int solution(int n, vector<vector<int>> edge) {
int answer = 0;
adj = vector<vector<int>>(n+1);
visited = vector<int>(n+1, -1);
for(int i=0; i<edge.size(); i++){
adj[edge[i][0]].push_back(edge[i][1]);
adj[edge[i][1]].push_back(edge[i][0]);
}
int t = bfs();
for(int i=1; i<=n; i++)
if(visited[i] == t) answer++;
return answer;
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[프로그래머스] 주식가격 (0) | 2020.04.02 |
---|---|
[프로그래머스] 가장 긴 팰린드롬 (0) | 2020.04.02 |
[프로그래머스] 2 x n 타일링 (0) | 2020.04.02 |
[프로그래머스] N으로 표현 (0) | 2020.04.02 |
[백준] 6198 옥상 정원 꾸미기 (0) | 2020.04.02 |