Created
September 3, 2015 18:24
-
-
Save cxtadment/e2f5d0c087914a5fd1ef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Definition for undirected graph. | |
| * class UndirectedGraphNode { | |
| * int label; | |
| * ArrayList<UndirectedGraphNode> neighbors; | |
| * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } | |
| * }; | |
| */ | |
| public class Solution { | |
| /** | |
| * @param node: A undirected graph node | |
| * @return: A undirected graph node | |
| */ | |
| public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { | |
| // write your code here | |
| if (node == null) { | |
| return null; | |
| } | |
| ArrayList<UndirectedGraphNode> nodes = new ArrayList<>(); | |
| HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>(); | |
| nodes.add(node); | |
| map.put(node, new UndirectedGraphNode(node.label)); | |
| //clone node | |
| int start = 0; | |
| while (start < nodes.size()) { | |
| UndirectedGraphNode tempnode = nodes.get(start++); | |
| for (int i = 0; i < tempnode.neighbors.size(); i++) { | |
| if (map.containsKey(tempnode.neighbors.get(i))) { | |
| continue; | |
| } else { | |
| nodes.add(tempnode.neighbors.get(i)); | |
| map.put(tempnode.neighbors.get(i), new UndirectedGraphNode(tempnode.neighbors.get(i).label)); | |
| } | |
| } | |
| } | |
| //clone neighbors | |
| for (int i = 0; i < nodes.size(); i++) { | |
| UndirectedGraphNode tempnode = nodes.get(i); | |
| UndirectedGraphNode cloneNode = map.get(tempnode); | |
| for (int j = 0; j < tempnode.neighbors.size(); j++) { | |
| cloneNode.neighbors.add(map.get(tempnode.neighbors.get(j))); | |
| } | |
| } | |
| return map.get(node); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment