LeetCode--133. Clone Graph
阿新 • • 發佈:2019-01-01
題目連結:https://leetcode.com/problems/clone-graph/
題目要求:圖的硬copy
這個一定是用圖的深度優先搜尋或者廣度優先搜尋來遍歷整個圖,遍歷到新的節點就開闢記憶體,並將該記憶體的物件引用加入到當前節點的鄰接表中去。這裡新的節點意味著還沒有加入硬拷貝圖的節點,而對於已經在圖中的節點我們需要把它的引用物件加入到當前節點的鄰接表中。為了避免重複生成新的節點,這裡使用HashMap<int,UndirectedGraphNode>既能去重(防止重複生成節點),又能儲存已存在於硬拷貝圖中的節點的引用。
當然,DFS用遞迴做,BFS用佇列來輔助。
深度優先搜尋程式碼:
/** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */ public class Solution { public HashMap<Integer,UndirectedGraphNode> record=new HashMap<Integer,UndirectedGraphNode>(); public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node==null) return null; if(record.containsKey(node.label)) return record.get(node.label); UndirectedGraphNode ret=new UndirectedGraphNode(node.label); record.put(node.label,ret); if(node.neighbors.size()!=0) { List<UndirectedGraphNode> temp=node.neighbors; for(UndirectedGraphNode tmpnode:temp) { ret.neighbors.add(cloneGraph(tmpnode)); } } return ret; } }
廣度優先搜尋程式碼:
/** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */ public class Solution { public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) return null; Map<Integer, UndirectedGraphNode> nodes = new HashMap<>(); Queue<UndirectedGraphNode> queue = new ArrayDeque<>(); queue.offer(node); nodes.put(node.label, new UndirectedGraphNode(node.label)); UndirectedGraphNode root = nodes.get(node.label); while(!queue.isEmpty()) { UndirectedGraphNode n = queue.poll(); UndirectedGraphNode copy = nodes.get(n.label); for(UndirectedGraphNode neighbor : n.neighbors) { if(!nodes.containsKey(neighbor.label)) { queue.offer(neighbor); nodes.put(neighbor.label, new UndirectedGraphNode(neighbor.label)); } copy.neighbors.add(nodes.get(neighbor.label)); } } return root; } }