佇列&棧//克隆圖
阿新 • • 發佈:2018-12-20
克隆一張無向圖,圖中的每個節點包含一個 label
(標籤)和一個 neighbors
(鄰接點)列表 。
OJ的無向圖序列化:
節點被唯一標記。
我們用 #
作為每個節點的分隔符,用 ,
作為節點標籤和鄰接點的分隔符。
例如,序列化無向圖 {0,1,2#1,2#2,2}
。
該圖總共有三個節點, 被兩個分隔符 #
分為三部分。
- 第一個節點的標籤為
0
,存在從節點0
到節點1
和節點2
的兩條邊。 - 第二個節點的標籤為
1
,存在從節點1
到節點2
的一條邊。 - 第三個節點的標籤為
2
,存在從節點2
到節點2
(本身) 的一條邊,從而形成自環。
我們將圖形視覺化如下:
1 / \ / \ 0 --- 2 / \ \_/
/** * 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; HashMap<UndirectedGraphNode,UndirectedGraphNode> hashMap = new HashMap<>(); LinkedList<UndirectedGraphNode> queue = new LinkedList<>(); UndirectedGraphNode head = new UndirectedGraphNode(node.label); hashMap.put(node,head); queue.offer(node); while(!queue.isEmpty()){ UndirectedGraphNode curNode = queue.poll(); for(UndirectedGraphNode neighbor:curNode.neighbors){ if(hashMap.containsKey(neighbor)==false){ queue.offer(neighbor); UndirectedGraphNode newNeighbor = new UndirectedGraphNode(neighbor.label); hashMap.put(neighbor,newNeighbor); } hashMap.get(curNode).neighbors.add(hashMap.get(neighbor)); } } return head; } }
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {//DFS if (node == null) return null; HashMap<UndirectedGraphNode, UndirectedGraphNode> hashMap = new HashMap<>(); UndirectedGraphNode head = new UndirectedGraphNode(node.label); hashMap.put(node, head); DFSSearch(hashMap, node); return head; } private void DFSSearch(HashMap<UndirectedGraphNode, UndirectedGraphNode> hashMap, UndirectedGraphNode node) { if (node == null) return; for (UndirectedGraphNode neighbor : node.neighbors) { if (hashMap.containsKey(neighbor) == false) { UndirectedGraphNode newNeighbor = new UndirectedGraphNode(neighbor.label); hashMap.put(neighbor, newNeighbor); DFSSearch(hashMap, neighbor); } hashMap.get(node).neighbors.add(hashMap.get(neighbor)); } }。
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
map<int,UndirectedGraphNode*> A;
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(!node) return NULL;
UndirectedGraphNode *p = new UndirectedGraphNode(node->label);
A[node->label] = p;
for(auto &x:node->neighbors)
if(!A.count(x->label)) p->neighbors.push_back(cloneGraph(x));
else p->neighbors.push_back(A[x->label]);
return p;
}
};