Skip to content

Commit 208aa9f

Browse files
author
Dhananjay Nagargoje
committed
EPI clone graph
1 parent 47a58c3 commit 208aa9f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Diff for: src/main/java/problems/ongraph/GraphClone.java

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+

0 commit comments

Comments
 (0)