130. Surrounded Regions
来源:互联网 发布:仙剑奇侠传mac无文字 编辑:程序博客网 时间:2024/06/06 13:16
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
OJ’s undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by #.
- First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
- Second node is labeled as 1. Connect node 1 to node 2.
- Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \0 --- 2 / \ \_/
题意:
无向图的复制
思路:
题目的难点在于如何处理每个节点的neighbors,由于在深度拷贝每一个节点后,还要将其所有neighbors放到一个vector中,如何避免重复拷贝呢?这道题好就好在所有节点值不同,所以我们可以使用哈希表来对应节点值和新生成的节点。对于图的遍历的两大基本方法是深度优先搜索DFS和广度优先搜索BFS,这里我们使用深度优先搜索DFS来解答此题:
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */class Solution {public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { unordered_map<int, UndirectedGraphNode*> umap; return clone(node, umap); } UndirectedGraphNode *clone(UndirectedGraphNode *node, unordered_map<int, UndirectedGraphNode*> &umap) { if (!node) return node; if (umap.count(node->label)) return umap[node->label]; UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label); umap[node->label] = newNode; for (int i = 0; i < node->neighbors.size(); ++i) { (newNode->neighbors).push_back(clone(node->neighbors[i], umap)); } return newNode; } };
参考资料:
http://www.cnblogs.com/grandyang/p/4267628.html
- [LeetCode]130.Surrounded Regions
- LeetCode 130. Surrounded Regions
- [leetcode] 130.Surrounded Regions
- 130. Surrounded Regions
- Leetcode 130. Surrounded Regions
- 130. Surrounded Regions
- 130. Surrounded Regions
- leetcode 130. Surrounded Regions
- leetcode 130. Surrounded Regions
- LeetCode 130. Surrounded Regions
- 130. Surrounded Regions
- [LeetCode]130. Surrounded Regions
- LeetCode 130. Surrounded Regions
- 130. Surrounded Regions
- LeetCode *** 130. Surrounded Regions
- 130. Surrounded Regions
- Leetcode 130. Surrounded Regions
- [leetcode] 130. Surrounded Regions
- 新的不良资产可能会出现在SBI
- butterknife 基本使用
- 递归算法练习题
- jquery 插件版本冲突处理
- 新闻客户端02 - 完善TabBar
- 130. Surrounded Regions
- 首页垂直滚动TextView广告效果,使用TextSwicher+animation实现
- HDUOJ5835Danganronpa&&2016中国大学生程序设计竞赛 - 网络选拔赛1004
- 插入排序(Java)
- spring-mvc框架学习初长成
- cpu_freq之切换governor.
- Linux进阶之路——LAMP架构搭建及常见问题
- Install SQL Server 2008 on a Windows Server 2008 Cluster Part 3
- poj1006生理周期