Clone Graph (leetcode133)DFS

想复杂了,搞了好久。

class Solution {
    public Node cloneGraph(Node first) {
        if (first==null)    return null;
        Stack<Node> stack = new Stack<>();
        HashMap<Node, Node> map = new HashMap<>();
        map.put(first,new Node(first.val));
        stack.push(first);
        while(!stack.isEmpty()){
            Node node = stack.pop();
            for (Node neighbor : node.neighbors) {
                if(!map.containsKey(neighbor)){
                    map.put(neighbor,new Node(neighbor.val));
                    stack.push(neighbor);
                }
                map.get(node).neighbors.add(map.get(neighbor));
            }
        }
        return map.get(first);
    }
}
class Node {
    public int val;
    public List<Node> neighbors;
    public Node() {
        val = 0;
        neighbors = new ArrayList<Node>();
    }
    public Node(int _val) {
        val = _val;
        neighbors = new ArrayList<Node>();
    }
    public Node(int _val, ArrayList<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
}

 

本文系作者 @ 原创发布在 噓だ。未经许可,禁止转载。

喜欢()
评论 (0)
热门搜索
37 文章
3 评论
11 喜欢
Top