1311.cpp (1152B)
1 class Solution { 2 public: 3 vector<string> watchedVideosByFriends(vector<vector<string>> &watchedVideos, vector<vector<int>> &adj, 4 int id, int level) { 5 int n = adj.size(); 6 vector<bool> visited(n, false); 7 queue<int> q; 8 9 q.push(id); 10 visited[id] = true; 11 for (int lvl = 0; lvl != level; lvl++) { 12 for (int k = q.size(); k > 0; k--) { 13 int id = q.front(); 14 q.pop(); 15 for (int c : adj[id]) { 16 if (!visited[c]) { 17 visited[c] = true; 18 q.push(c); 19 } 20 } 21 } 22 } 23 24 unordered_map<string, int> freq; 25 vector<pair<int, string>> vec; 26 vector<string> res; 27 28 for (; !q.empty(); q.pop()) 29 for (auto &st : watchedVideos[q.front()]) 30 freq[st]++; 31 32 for (auto &[k, v] : freq) 33 vec.push_back({v, k}); 34 sort(vec.begin(), vec.end()); 35 for (auto &[_, title] : vec) 36 res.push_back(title); 37 return res; 38 } 39 };