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; } }
本文系作者 @rinbn 原创发布在 噓だ。未经许可,禁止转载。