File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ // Definition for a Node.
3+ class Node {
4+ public int val;
5+ public List<Node> neighbors;
6+ public Node() {
7+ val = 0;
8+ neighbors = new ArrayList<Node>();
9+ }
10+ public Node(int _val) {
11+ val = _val;
12+ neighbors = new ArrayList<Node>();
13+ }
14+ public Node(int _val, ArrayList<Node> _neighbors) {
15+ val = _val;
16+ neighbors = _neighbors;
17+ }
18+ }
19+ */
20+
21+ class CloneGraph { //create a deep copy of the given graph
22+ public Node cloneGraph (Node node ) {
23+ Queue <Node > q = new LinkedList <>();
24+
25+ if (node == null ){
26+ return node ;
27+ }
28+
29+ q .add (node );
30+
31+ Map <Node , Node > map = new HashMap <>();
32+ Node current ;
33+
34+ Node newNode = new Node ();
35+ newNode .val = node .val ;
36+ map .put (node , newNode );
37+
38+ while (!q .isEmpty ()){
39+ current = q .poll ();
40+ Node currentClone = map .get (current );
41+
42+ for (Node neighboringNode : current .neighbors ){
43+ if (map .containsKey (neighboringNode )){
44+ currentClone .neighbors .add (map .get (neighboringNode ));
45+ }
46+ else {
47+ Node newCloneNeighbor = new Node (neighboringNode .val );
48+ map .put (neighboringNode , newCloneNeighbor );
49+ q .add (neighboringNode );
50+ currentClone .neighbors .add (newCloneNeighbor );
51+ }
52+ }
53+ }
54+
55+ return map .get (node );
56+ }
57+ }
You can’t perform that action at this time.
0 commit comments