File tree 1 file changed +42
-0
lines changed
src/main/java/problems/ongraph
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ package problems .ongraph ;
2
+
3
+
4
+ import java .util .*;
5
+
6
+ public class GraphClone {
7
+
8
+ public static class GraphVertex {
9
+ public int label ;
10
+ public List <GraphVertex > edges ;
11
+
12
+ public GraphVertex (int label ) {
13
+ this .label = label ;
14
+ edges = new ArrayList <>();
15
+ }
16
+ }
17
+
18
+ public static GraphVertex cloneGraph (GraphVertex graph ) {
19
+
20
+ if (graph == null ) {
21
+ return null ;
22
+ }
23
+
24
+ Map <GraphVertex , GraphVertex > vertexMap = new HashMap <>();
25
+ Queue <GraphVertex > q = new ArrayDeque <>();
26
+ q .add (graph );
27
+ vertexMap .put (graph , new GraphVertex (graph .label ));
28
+ while (!q .isEmpty ()) {
29
+ GraphVertex v = q .remove ();
30
+ for (GraphVertex e : v .edges ) {
31
+ // Try to copy vertex e.
32
+ if (vertexMap .putIfAbsent (e , new GraphVertex (e .label )) == null ) {
33
+ q .add (e );
34
+ }
35
+ // Copy edge.
36
+ vertexMap .get (v ).edges .add (vertexMap .get (e ));
37
+ }
38
+ }
39
+ return vertexMap .get (graph );
40
+ }
41
+ }
42
+
You can’t perform that action at this time.
0 commit comments