Https://leetcode.com/problems/accounts-merge/discuss/109158/Java-Solution-(build-graph-+-DFS-search)
1 class solution {2 public list <string> accountsmerge (list <string> accounts) {3 list <string> res = new arraylist <> (); 4 If (Accounts = NULL) return res; 5 hashmap <string, string> map = new hashmap <> (); 6 hashmap <string, set <string> graph = new hashmap <> (); 7 for (Int J = 0; j <accounts. size (); j ++) {8 list <string> account = accounts. get (j); 9 string name = account. get (0); 10 (INT I = 1; I <account. Size (); I ++) {11 if (! Graph. containskey (account. get (I) {12 graph. put (account. get (I), new hashset <> (); 13} 14 map. put (account. get (I), name); 15 16 if (I! = 1) {17 graph. get (account. get (I )). add (account. get (I-1); 18 graph. get (account. get (I-1 )). add (account. get (I); 19} 20} 21} 22 23 set <string> visited = new hashset <> (); 24 for (string Email: map. keyset () {25 list <string> List = new arraylist <> (); 26 string name = map. get (email); 27 if (! Visited. contains (email) {// determine whether visited is enabled. If not, add 28 visited. add (email); 29 DFS (graph, visited, list, email); 30 collections. sort (list); 31 List. add (0, name); 32 res. add (list); 33} 34} 35 return res; 36} 37 38 public void DFS (hashmap <string, set <string> graph, set <string> visited, list <string> list, string email) {39 list. add (email); 40 for (string neighbor: graph. get (email) {41 if (! Visited. Contains (neighbor) {42 visited. Add (neighbor); 43 DFS (graph, visited, list, neighbor); 44} 45} 46} 47}
721. Accounts merge