【发布时间】:2019-11-24 16:35:17
【问题描述】:
我必须在 C 中分析一个 m-ary 树 - 使用 BFS。
有一些要求我暂时没有成功实现:
1.求树的直径。
2。给定树中的两个顶点 - 找到它们之间的最短简单路径。
至于 1 - 我浏览了 Stack 中的主题 - 并且看到了一些对我来说不是很清楚的实现(不幸的是不是在 C 中)......通过使用 BFS 两次来计算直径的某种方法,从随机顶点... 我不确定第二个 BFS 是否必须“记住”第一个 BFS 中访问过的数组。
至于 2 - 我真的不知道该怎么做,但我相信我可以在这里使用 BFS。
而且,我必须以 O(n^2) 的时间复杂度来实现这两个要求。
除此之外,我还必须找到树的最大和最小高度。
至于最大高度 - 我已经实施了 BFS(不确定它是否绝对正确)据我了解,它处理这个最大高度。
至于最小高度 - 我不知道如何找到它。
这是我的顶点结构和 BFS 实现:
typedef struct Vertex {
size_t key;
size_t amountOfNeighbors; // The current amount of neighbors
size_t capacity; // The capacity of the neighbors (It's updating during run-time)
struct Vertex* parent;
struct Vertex** neighbors; // The possible parent and children of a vertex
} Vertex;
Vertex* bfs(Vertex* allVertices, size_t numOfVertices, Vertex* startVertex, size_t* pathDistance) {
if (startVertex -> neighbors == NULL) { // In case we have only one vertex in the graph
*pathDistance = 0;
return startVertex;
}
Queue* q = (Queue*)malloc((sizeof(size_t) * numOfVertices));
int* visited = (int*)malloc(sizeof(int) * numOfVertices);
for (size_t i = 0; i < numOfVertices; i++) {
visited[i] = 0; // Mark all the vertices as unvisited
}
size_t lastVertex = 0; // Actually indicates the furthermost vertex from startVertex
*pathDistance = 0; // The number of edges between lastVertex and startVertex
enqueue(q, startVertex->key);
visited[startVertex->key] = 1; // Mark as visited
while (!queueIsEmpty(q)) {
unsigned int currentVertex = dequeue(q); // The key of the current vertex
Vertex* s = &allVertices[currentVertex];
size_t currentAmountOfNeighbors = 0; // Detects the number of processed neighbors of the current vertex
for (Vertex **child = s->neighbors; currentAmountOfNeighbors < s->amountOfNeighbors; currentAmountOfNeighbors++) {
if (!visited[(*(child))->key]) {
visited[(*(child))->key] = 1;
enqueue(q, (*(child))->key);
child++; // TODO Validate it's a correct use of memory!
}
}
*pathDistance += 1; // Another layer passed
lastVertex = peekQueue(q);
}
Vertex* furtherMostVertexFromS = &allVertices[lastVertex];
free(q);
q = NULL;
return furtherMostVertexFromS;
}
我的困难和疑惑以粗体显示,我们将不胜感激。
【问题讨论】:
标签: c pointers path height breadth-first-search