题目:
Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.
class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.
An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.
Constraints:
The number of nodes in the graph is in the range [0, 100].
1 <= Node.val <= 100
Node.val is unique for each node.
There are no repeated edges and no self-loops in the graph.
The Graph is connected and all nodes can be visited starting from the given node.
我的解答:
#include<bits/stdc++.h>
using namespace std;
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
// 思路:一边遍历原来的图。一边新建新的图,处理好int val和vector<Node*> neighbors两个字段
// 邻接节点又分为正要创建的和已经创建了,两种情况
class Solution {
public:
Node* cloneGraph(Node* node) {
if(!node) return nullptr;
return bfs(node);
}
Node* bfs(Node* rootNode){
queue<Node*> myQueue;
// 用来标记哪些节点访问过了。 false表示没有访问过,true表示访问过
vector<bool> visited(100 + 10, false);
// 泛型,int表示节点的值val,Node*表示该节点对应的指针或者地址
map<int, Node*> myMap;
// 在这个题目里rootNode -> val肯定是1
Node* resultNode = new Node(rootNode -> val);
myMap[rootNode -> val] = resultNode;
myQueue.push(rootNode);
visited[rootNode -> val] = true;
while(!myQueue.empty()){
Node* frontNode = myQueue.front();
myQueue.pop();
// 复制自己的邻接节点: 遍历当前节点的邻接节点,同步建立新的节点和图。
// 邻接节点vector<Node*> neighbors,有新建的,也有已经建立好的
// vector<Node*>::iterator it = (*frontNode).neighbors.begin();
vector<Node*>::iterator it = frontNode -> neighbors.begin();
for( ; it != frontNode -> neighbors.end(); it ++ ){
// 邻接节点的值
// int value2 = it -> val;
int value = (*it) -> val;
// printf("value: %d\n", value);
// 还没访问过
if( visited[value] == false ){
// 这下访问过了
visited[value] = true;
// 为了后续的dfs
myQueue.push( (*it) );
// myQueue.push( it );
Node* newNode = new Node(value);
myMap[value] = newNode;
// 就是下边两句话的问题
// frontNode -> neighbors.push_back(newNode);
myMap[frontNode->val] -> neighbors.push_back(newNode);
printf("新建节点的value: %d\n", value);
}else{ // 访问过了的呢
myMap[frontNode->val] -> neighbors.push_back(myMap[value]);
printf("创建好的节点的value: %d\n", value);
}
}
}
return resultNode;
}
};