@@ -53,18 +53,110 @@ Another solution is [-3,1,4,-2], which would also be accepted.
53
53
54
54
## Solutions
55
55
56
+ Traverse the graph from the point where the degree is one.
57
+
56
58
<!-- tabs:start -->
57
59
58
60
### ** Python3**
59
61
60
62
``` python
61
-
63
+ class Solution :
64
+ def restoreArray (self , adjacentPairs : List[List[int ]]) -> List[int ]:
65
+ graph = collections.defaultdict(list )
66
+ for pair in adjacentPairs:
67
+ graph[pair[0 ]].append(pair[1 ])
68
+ graph[pair[1 ]].append(pair[0 ])
69
+ ans = []
70
+ vis = set ()
71
+
72
+ def dfs (idx ):
73
+ if idx in vis:
74
+ return
75
+ vis.add(idx)
76
+ ans.append(idx)
77
+ for nxt in graph[idx]:
78
+ dfs(nxt)
79
+
80
+ start = - 1
81
+ for idx, adj in graph.items():
82
+ if len (adj) == 1 :
83
+ start = idx
84
+ break
85
+
86
+ dfs(start)
87
+ return ans
62
88
```
63
89
64
90
### ** Java**
65
91
66
92
``` java
93
+ class Solution {
94
+ public int [] restoreArray (int [][] adjacentPairs ) {
95
+ Map<Integer , List<Integer > > graph = new HashMap<> ();
96
+ for (int [] pair : adjacentPairs) {
97
+ graph. putIfAbsent(pair[0 ], new ArrayList<> ());
98
+ graph. putIfAbsent(pair[1 ], new ArrayList<> ());
99
+ graph. get(pair[0 ]). add(pair[1 ]);
100
+ graph. get(pair[1 ]). add(pair[0 ]);
101
+ }
102
+ List<Integer > ans = new ArrayList<> ();
103
+ Set<Integer > vis = new HashSet<> ();
104
+ int start = - 1 ;
105
+ for (Map . Entry<Integer , List<Integer > > entry : graph. entrySet()) {
106
+ if (entry. getValue(). size() == 1 ) {
107
+ start = entry. getKey();
108
+ break ;
109
+ }
110
+ }
111
+ dfs(graph, ans, vis, start);
112
+ return ans. stream(). mapToInt(Integer :: valueOf). toArray();
113
+ }
114
+
115
+ private void dfs (Map<Integer , List<Integer > > graph , List<Integer > ans , Set<Integer > vis , int idx ) {
116
+ if (vis. contains(idx)) {
117
+ return ;
118
+ }
119
+ vis. add(idx);
120
+ ans. add(idx);
121
+ for (Integer next : graph. get(idx)) {
122
+ dfs(graph, ans, vis, next);
123
+ }
124
+ }
125
+ }
126
+ ```
67
127
128
+ ### ** Go**
129
+
130
+ ``` go
131
+ func restoreArray (adjacentPairs [][]int ) []int {
132
+ graph := make (map [int ][]int )
133
+ for _ , pair := range adjacentPairs {
134
+ graph[pair[0 ]] = append (graph[pair[0 ]], pair[1 ])
135
+ graph[pair[1 ]] = append (graph[pair[1 ]], pair[0 ])
136
+ }
137
+ ans := make ([]int , 0 )
138
+ vis := make (map [int ]bool )
139
+ var start int
140
+ for idx , adj := range graph {
141
+ if len (adj) == 1 {
142
+ start = idx
143
+ break
144
+ }
145
+ }
146
+ dfs (graph, &ans, vis, start)
147
+ return ans
148
+ }
149
+
150
+ func dfs (graph map [int ][]int , ans *[]int , vis map [int ]bool , idx int ) {
151
+ if vis[idx] {
152
+ return
153
+ }
154
+ vis[idx] = true
155
+ *ans = append (*ans, idx)
156
+ for _ , next := range graph[idx] {
157
+ dfs (graph, ans, vis, next)
158
+ }
159
+ }
68
160
```
69
161
70
162
### ** ...**
0 commit comments