1+ /*
2+ 1. 아이디어:
3+ - 그래프 구조에서 특정 노드 기준 거리가 k인 노드들을 체크
4+ - 그 노드들의 비디오 자료를 확인 후 커스텀 정렬 (1. 빈도수 2. 알파벳)
5+ - 비디오 제목은 가짓수가 26^8이므로 hashmap 자료구조 사용
6+ - 또한 friends가 이미 그래프 구조이므로 별도 그래프 구조체를 만들지 않음
7+
8+ 2. 시간복잡도: O(N + E + U log U) (N: 친구 수, E: 친구 관계 수, U: 고유 비디오 수)
9+
10+ 3. 자료구조/알고리즘: BFS + 커스텀 정렬 + HashMap
11+ */
12+ class Solution {
13+
14+ private class Info {
15+ String title ;
16+ int cnt ;
17+
18+ public Info (String title , int cnt ) {
19+ this .title = title ;
20+ this .cnt = cnt ;
21+ }
22+ };
23+
24+ public List <String > watchedVideosByFriends (List <List <String >> watchedVideos , int [][] friends , int id , int level ) {
25+
26+ List <Integer > friend = bfs (friends , id , level );
27+
28+ Map <String , Integer > map = new HashMap <>();
29+
30+ // 비디오 계산
31+ for (int i : friend ) {
32+ for (String video : watchedVideos .get (i )) {
33+ if (!map .containsKey (video )) map .put (video , 1 );
34+ else map .put (video ,map .get (video )+1 );
35+ }
36+ }
37+
38+ List <Info > info = new ArrayList <>();
39+
40+ // 구조체 삽입
41+ for (String key : map .keySet ()) {
42+ info .add (new Info (key , map .get (key )));
43+ }
44+
45+ Collections .sort (info , (a ,b ) ->{
46+ if (a .cnt == b .cnt ) return a .title .compareTo (b .title );
47+ return a .cnt - b .cnt ;
48+ });
49+
50+ List <String > ans = new ArrayList <>();
51+
52+ for (Info i : info ) {
53+ ans .add (i .title );
54+ }
55+
56+ return ans ;
57+ }
58+
59+ private List <Integer > bfs (int [][] friends , int id , int level ){
60+ Deque <int []> dq = new ArrayDeque <>();
61+ boolean [] visited = new boolean [friends .length ];
62+
63+ List <Integer > friend = new ArrayList <>();
64+
65+ dq .add (new int []{id , 0 });
66+ visited [id ] = true ;
67+
68+ while (!dq .isEmpty ()) {
69+ int curr [] = dq .poll ();
70+
71+ int currId = curr [0 ];
72+ int depth = curr [1 ];
73+
74+ if (depth == level ) friend .add (currId );
75+
76+ for (int next : friends [currId ]) {
77+
78+ if (visited [next ] || depth >level ) continue ;
79+
80+ dq .add (new int []{next ,depth +1 });
81+ visited [next ] = true ;
82+ }
83+ }
84+
85+ return friend ;
86+ }
87+ }
0 commit comments