无向图拷贝(clone-graph)

思路:

  1. 用深度优先(DFS)进行遍历
  2. 用map保存新旧值的映射关系

代码:

struct UndirectedGraphNode {
	int label;
    vector neighbors;
    UndirectedGraphNode(int x) : label(x) {};
};

class Solution {
public:
	map m;
	UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
		if (!node)
			return NULL;
		return dfs(node);
	}

	UndirectedGraphNode *dfs(UndirectedGraphNode *node) {
		map::iterator iter = m.find(node);
		if (iter != m.end())
			return iter->second;
		UndirectedGraphNode *p = new UndirectedGraphNode(node->label);
		m.insert(pair(node, p));
		for (int i = 0; i < node->neighbors.size(); ++i) {
			p->neighbors.push_back(dfs(node->neighbors[i]));
		}
		return p;
	}
};

 

你可能感兴趣的:(ACM,图拷贝,无向图,map,clone-graph)