classSolution {intDFS (vector<int>&res,inti,vector<int>& quiet,map<int,vector<int>>&m) { if(res[i]>0)returnRes[i]; Res[i]=i; for(intj=0; J<m[i].size (); + +j) { if(quiet[res[i]]>Quiet[dfs (res,m[i][j],quiet,m)]) Res[i]=Res[m[i][j]]; } returnRes[i]; } Public: Vector<int> Loudandrich (vector<vector<int>>& Richer, vector<int>&quiet) {Map<int,vector<int>>m; for(auto&v:richer) {m[v[1]].push_back (v[0]); } Vector<int> res=vector<int> (Quiet.size (),-1); for(intI=0; I<quiet.size (); + +i) {DFS (RES,I,QUIET,M); } returnRes; }};
Python code
classSolution (Object): Def loudandrich (self, richer, quiet):""": Type richer:list[list[int]]: type quiet:list[int]: rtype:list[int] """m=collections.defaultdict (list) forI,jinchricher:m[j].append (i) Res=[-1]*Len (quiet) def dfs (i):ifRes[i]>0: returnRes[i] Res[i]=I forJinchM[i]:ifQuiet[res[i]]>Quiet[dfs (j)]: Res[i]=Res[j]returnRes[i] forIinchRange (len (res)): DFS (i)returnRes
Leetcode 851. Loud and Rich