Leetcode题解 - 中等难度(1311、LCP 3、1306、1282、1296、1297)
1311. 获取你好友已观看的视频 - BFS 思路: 找到第level层的好友,是一层一层寻找所以使用BFS,然后再计数就行了 """ BFS """ from collections import defaultdict, Counter class Solution: def watchedVideosByFriends(self, watchedVideos, friends, id: int, level: int): mat = defaultdict(list) # 先建图 for ind, num in enumerate(friends): mat[ind] += num Q, vis = [(id, 0)], {id} # BFS找level层的朋友是谁 while len(Q) != 0: node, deepth = Q.pop(0) if deepth == level: Q = [i[0] for i in Q] + [node] break for i in mat[node]: if i not in vis: vis.add(i) Q.append((i, deepth+1)) res = [] for i in Q: res += watchedVideos[i] r = sorted(Counter(res).items(), key