Skip to content

Commit de6010f

Browse files
Create 1743-restore-the-array-from-adjacent-pairs.java
1 parent 4b36cc0 commit de6010f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Diff for: java/1743-restore-the-array-from-adjacent-pairs.java

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public static int[] restoreArray(int[][] adjacentPairs) {
3+
Map<Integer, List<Integer>> g = new HashMap<>();
4+
for(int[] p: adjacentPairs){
5+
int a = p[0], b = p[1];
6+
g.computeIfAbsent(a,val -> new ArrayList<>()).add(b);
7+
g.computeIfAbsent(b,val -> new ArrayList<>()).add(a);
8+
}
9+
int source = 0;
10+
for(int node: g.keySet()){
11+
if(g.get(node).size() == 1){
12+
source = node;
13+
break;
14+
}
15+
}
16+
int[] res = new int[adjacentPairs.length+1];
17+
Set<Integer> visited = new HashSet<>();
18+
dfs(g, source, res, visited, 0);
19+
return res;
20+
}
21+
private static void dfs(Map<Integer, List<Integer>> g, int node, int[] res, Set<Integer> visited, int i){
22+
res[i++] = node;
23+
visited.add(node);
24+
25+
for(int ne: g.get(node)){
26+
if(!visited.contains(ne))
27+
dfs(g, ne, res, visited, i);
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)