思路:
① 遍歷圖,記錄下所有的節點和邊。
② 將數值與指針一一對應。
③ 新建節點,並根據邊的關係把它的相連節點加進vector<Node*>
。
class Solution {
public:
Node* nodeList[110] = {0};
vector<int> graph[110];
int vis[110] = {0};
Node* cloneGraph(Node* node) {
if(!node){
return nullptr;
}
if(!node->neighbors.size()){
return new Node(1);
}
queue<Node*> q;
q.push(node);
vis[1] = 1;
while(q.size()){
Node * px = q.front();
q.pop();
int x = px->val;
for(Node* py: px->neighbors){
int y = py->val;
graph[x].push_back(y);
//每個點只會被入隊一次
if(!vis[y]){
q.push(py);
}
vis[y] = 1;
}
}
for(int i=1;i<=100;i++){
if(graph[i].size()){
nodeList[i] = new Node(i);
}
}
for(int x=1;x<=100;x++){
if(graph[x].size()){
for(int y:graph[x])
nodeList[x]->neighbors.push_back(nodeList[y]);
}
}
return nodeList[1];
}
};