Leetcode 133. Clone Graph 一问?

2019-06-17 02:38:26 +08:00
 qwertyegg

这段代码什么问题?

public Node cloneGraph(Node node) {
        if(node == null) return null;

        Map<Node, Node> map = new HashMap();
        Queue<Node> queue = new LinkedList();
        List<Node> store = new ArrayList();
        queue.offer(node);
        Node current;
        while(!queue.isEmpty()){
            current = queue.poll();
            map.put(current, new Node(current.val, new ArrayList(current.neighbors.size())));
            store.add(current);
            for(Node neighbor : current.neighbors)
                if(!map.keySet().contains(neighbor))
                    queue.offer(neighbor);
        }

        for(Node n : store)
            for(Node neighbor : n.neighbors)
                map.get(n).neighbors.add(map.get(neighbor));
        return map.get(node);
    }

input:

{"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},{"$id":"3","neighbors":[{"$ref":"2"},{"$id":"4","neighbors":[{"$ref":"3"},{"$ref":"1"}],"val":4}],"val":3}],"val":2},{"$ref":"4"}],"val":1}

output:

{"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},{"$id":"3","neighbors":[{"$ref":"2"},{"$id":"4","neighbors":[{"$ref":"3"},{"$ref":"1"}],"val":4},{"$ref":"2"},{"$ref":"4"}],"val":3}],"val":2},{"$ref":"4"}],"val":1}

expected output:

{"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},{"$id":"3","neighbors":[{"$ref":"2"},{"$id":"4","neighbors":[{"$ref":"3"},{"$ref":"1"}],"val":4}],"val":3}],"val":2},{"$ref":"4"}],"val":1}
13935 次点击
所在节点    LeetCode
1 条回复
pwrliang
2019-06-17 14:22:02 +08:00
因为你使用 BFS,题目给的例子中:
1--2
| |
4--3

1 入队,1 出队,然后 2,4 入队;然后 2 出队,1 访问过了跳过,3 入队;然后 4 出队,1 访问过了跳过,3 入队。
此时,你发现队列存在两个“ 3 ”,造成了重复访问。因此,你在入队前应该检查入队的元素是否访问过。
把你的代码:
for(Node neighbor : current.neighbors)
if(!map.keySet().contains(neighbor))
queue.offer(neighbor);
改成:
for (Node neighbor : current.neighbors)
if (!map.keySet().contains(neighbor)) {
// 检查是否访问过,即可 AC
map.put(neighbor, new Node(neighbor.val, new ArrayList(neighbor.neighbors.size())));
queue.offer(neighbor);
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/574570

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX