File tree 1 file changed +33
-1
lines changed
1 file changed +33
-1
lines changed Original file line number Diff line number Diff line change @@ -40,6 +40,8 @@ You don't need to understand the serialization to solve the problem.
40
40
* }
41
41
*/
42
42
43
+
44
+ // SOLUTION 1 Using DFS
43
45
/**
44
46
* @param {UndirectedGraphNode } graph
45
47
* @return {UndirectedGraphNode }
@@ -64,4 +66,34 @@ var dfs = function(graph, visited) {
64
66
}
65
67
66
68
return newNode ;
67
- }
69
+ }
70
+
71
+ // SOLUTION 2 Using DFS
72
+ var cloneGraphBFS = function ( graph ) {
73
+ if ( graph === null )
74
+ return graph ;
75
+
76
+ var visitedMap = { } ;
77
+ var queue = [ graph ] ;
78
+ var copyReturn = new UndirectedGraphNode ( graph . label ) ;
79
+ visitedMap [ graph . label ] = copyReturn ;
80
+
81
+ while ( queue . length > 0 ) {
82
+ var node = queue . shift ( ) ;
83
+ var nodeCopied = visitedMap [ node . label ] ;
84
+
85
+ for ( var i = 0 ; i < node . neighbors . length ; i ++ ) {
86
+ var neighbor = node . neighbors [ i ] ;
87
+
88
+ if ( ! visitedMap [ neighbor . label ] ) {
89
+ var copyNeighbor = new UndirectedGraphNode ( neighbor . label ) ;
90
+ visitedMap [ neighbor . label ] = copyNeighbor ;
91
+ queue . push ( neighbor ) ;
92
+ }
93
+
94
+ nodeCopied . neighbors . push ( visitedMap [ neighbor . label ] ) ;
95
+ }
96
+ }
97
+
98
+ return copyReturn ;
99
+ }
You can’t perform that action at this time.
0 commit comments