Skip to content

Commit 06ab501

Browse files
committed
[level 3] Title: 가장 먼 노드, Time: 54.44 ms, Memory: 107 MB -BaekjoonHub
1 parent 63da42a commit 06ab501

File tree

2 files changed

+32
-29
lines changed

2 files changed

+32
-29
lines changed

프로그래머스/3/49189. 가장 먼 노드/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
### 성능 요약
66

7-
메모리: 108 MB, 시간: 34.23 ms
7+
메모리: 107 MB, 시간: 54.44 ms
88

99
### 구분
1010

@@ -16,7 +16,7 @@
1616

1717
### 제출 일자
1818

19-
2025년 03월 27일 13:10:28
19+
2025년 05월 23일 15:50:21
2020

2121
### 문제 설명
2222

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import java.util.*;
22

33
class Solution {
4-
List<Integer>[] tree;
4+
int n;
5+
List<Integer>[] graph;
56
boolean[] visited;
67
int[] d;
78
public int solution(int n, int[][] edge) {
@@ -12,52 +13,54 @@ public int solution(int n, int[][] edge) {
1213
}
1314

1415
int bfs(){
15-
int ans, max;
16-
Queue<Integer> q = new ArrayDeque();
17-
q.add(1);
16+
PriorityQueue<node> q = new PriorityQueue<>((o1, o2) -> o1.d - o2.d);
17+
q.add(new node(1, 1));
1818
visited[1] = true;
19+
1920

20-
int next, now;
21+
int next, answer;
22+
node now;
23+
answer = 0;
2124
while(!q.isEmpty()){
2225
now = q.poll();
2326

24-
for(int i = 0; i < tree[now].size(); i++){
25-
next = tree[now].get(i);
26-
27+
answer = Math.max(answer, now.d);
28+
d[now.d] += 1;
29+
for(int i = 0; i < graph[now.n].size(); i++){
30+
next = graph[now.n].get(i);
2731
if(visited[next]) continue;
28-
visited[next] = true;
29-
d[next] = d[now] + 1;
3032

31-
q.add(next);
33+
visited[next] = true;
34+
q.add(new node(next, now.d + 1));
3235
}
3336
}
34-
35-
Arrays.sort(d);
36-
ans = 0;
37-
max = d[d.length - 1];
38-
for(int i = d.length - 1; 0 < i; i--){
39-
40-
if(d[i] < max) break;
41-
ans++;
42-
}
43-
return ans;
37+
return d[answer];
4438
}
4539

4640
void preSetting(int n, int[][] edge){
47-
tree = new ArrayList[n + 1];
48-
d = new int[n + 1];
41+
this.n = n;
42+
graph = new ArrayList[n + 1];
4943
visited = new boolean[n + 1];
50-
visited[1] = true;
44+
d = new int[n + 1];
5145

52-
for(int i = 0; i < n + 1; i++) tree[i] = new ArrayList<>();
46+
for(int i = 0; i < n + 1; i++) graph[i] = new ArrayList<>();
5347

5448
int a, b;
5549
for(int i = 0; i < edge.length; i++){
5650
a = edge[i][0];
5751
b = edge[i][1];
5852

59-
tree[a].add(b);
60-
tree[b].add(a);
53+
graph[a].add(b);
54+
graph[b].add(a);
55+
}
56+
}
57+
58+
class node{
59+
int n, d;
60+
61+
node(int n, int d){
62+
this.n = n;
63+
this.d = d;
6164
}
6265
}
6366
}

0 commit comments

Comments
 (0)