Short Java DFS Solution

  • 0
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
    	if (node == null)
    		return null;
    	Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap();
    	return dfs(node, map);
    private UndirectedGraphNode dfs(UndirectedGraphNode node,
    		Map<UndirectedGraphNode, UndirectedGraphNode> map) {
    	if (map.containsKey(node))
    		return map.get(node);
    	UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
    	map.put(node, newNode);
    	for (int i = 0; i < node.neighbors.size(); i++) {
    		newNode.neighbors.add(dfs(node.neighbors.get(i), map));
    	return newNode;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.