leetcode Ch7-Graph Search

时间:2023-01-08 16:53:40

1. Clone Graph

BFS:

 class Solution {
public:
typedef UndirectedGraphNode UGNode;
UndirectedGraphNode* cloneGraph(UndirectedGraphNode* node) {
if (node == NULL) {
return NULL;
}
vector<UGNode*> nodes;
unordered_map<UGNode*, UGNode*> umap; //clone nodes only
nodes.push_back(node);
umap[node] = new UGNode(node->label);
int start = ;
while (start < nodes.size()) {
UGNode* tmp = nodes[start];
start++;
for (int i = ; i < tmp->neighbors.size(); i++) {
if (umap.count(tmp->neighbors[i]) == ) {
nodes.push_back(tmp->neighbors[i]);
umap[tmp->neighbors[i]] = new UGNode(tmp->neighbors[i]->label);
}
}
} //clone neighbors only
for (int i = ; i < nodes.size(); i++) {
UGNode* newNode = umap[nodes[i]];
for (int j = ; j < nodes[i]->neighbors.size(); j++) {
newNode->neighbors.push_back(umap[nodes[i]->neighbors[j]]);
}
}
return umap[node];
}
};

DFS:

 class Solution {
public:
typedef UndirectedGraphNode UGNode;
UndirectedGraphNode* cloneGraph(UndirectedGraphNode* node) {
if (node == NULL) {
return NULL;
}
return dfs(node);
} UGNode* dfs(UGNode* node) {
UGNode* p = new UGNode(node->label);
umap[p->label] = p;
for (int i = ; i < node->neighbors.size(); i++) {
if (umap.count(node->neighbors[i]->label) == ) {
p->neighbors.push_back(dfs(node->neighbors[i]));
} else {
p->neighbors.push_back(umap[node->neighbors[i]->label]);
}
}
return p;
}
private:
unordered_map<int, UGNode*> umap;
};

这里umap里的second存的都是copy后的图节点,不是原图。

图的邻接表DFS:

 struct VertexNode {
int data;
EdgeNode* next;
}; struct EdgeNode {
int index; // 存储其对应的点的下标
EdgeNode* next;
}; struct Graph {
VertexNode vexs[MAXVEX];
int numVertex;
}; vector<bool> visited; void dfs(Graph* g, int i) {
visited[i] = ;
print(g, i);
EdgeNode* p = g->vexs[i]->next;
while (p) {
if (!visited[p->index]) {
dfs(g, p->index);
}
p = p->next;
}
} void dfsTraverse(Graph* g) {
for (int i = ; i < g->numVertex; i++) {
if (!visited[i]) {
dfs(g, i);
}
}
}

图的邻接表BFS:

 void bfsTraverse(Graph* g) {
queue<int> q;
for (int i = ; i < numVertex; i++) {
if (!visited[i]) {
visited[i] = ;
print(g, i);
q.push(i);
while (!q.empty()) {
int j = q.top();
q.pop();
EdgeNode* p = g->vexs[j].next;
while (p) {
if (!visited[p->index]) {
visited[p->index] = ;
print(g, p->index);
q.push(p->index);
}
p = p->next;
}
}
}
}
}