File tree 2 files changed +44
-0
lines changed
2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ package classes ;
2
+
3
+ import java .util .*;
4
+
5
+ /**
6
+ * Created by fishercoder1534 on 9/30/16.
7
+ */
8
+ public class UndirectedGraphNode {
9
+ public int label ;
10
+ public List <UndirectedGraphNode > neighbors ;
11
+ public UndirectedGraphNode (int x ) { label = x ; neighbors = new ArrayList <UndirectedGraphNode >(); }
12
+ }
Original file line number Diff line number Diff line change
1
+ package medium ;
2
+
3
+ import classes .UndirectedGraphNode ;
4
+ import java .util .*;
5
+
6
+ /**
7
+ * Created by fishercoder1534 on 9/30/16.
8
+ */
9
+ public class CloneGraph {
10
+
11
+ public UndirectedGraphNode cloneGraph (UndirectedGraphNode node ) {
12
+ if (node == null ) return node ;
13
+
14
+ Map <Integer , UndirectedGraphNode > map = new HashMap ();
15
+ Queue <UndirectedGraphNode > queue = new LinkedList ();
16
+ UndirectedGraphNode root = new UndirectedGraphNode (node .label );
17
+ map .put (root .label , root );
18
+ queue .offer (node );//remember to offer the original input node into the queue which contains all the information
19
+ while (!queue .isEmpty ()){
20
+ UndirectedGraphNode curr = queue .poll ();
21
+ for (UndirectedGraphNode eachNode : curr .neighbors ){
22
+ if (!map .containsKey (eachNode .label )){
23
+ map .put (eachNode .label , new UndirectedGraphNode (eachNode .label ));
24
+ queue .offer (eachNode );
25
+ }
26
+ map .get (curr .label ).neighbors .add (map .get (eachNode .label ));
27
+ }
28
+ }
29
+ return root ;
30
+ }
31
+
32
+ }
You can’t perform that action at this time.
0 commit comments