c - 在C中计算邻接表图中每个顶点的入度
问题描述
我有一个使用邻接表表示实现的图。我想计算指向每个顶点的边数(顶点的入度)。
这是一个图表:
Vertex 0: 3 -> 2 -> 1 ->
Vertex 1: 4 ->
Vertex 2: 6 -> 1 -> 5 -> 4 ->
Vertex 3: 4 -> 5 -> 6 -> 0 ->
Vertex 4: 6 -> 2 -> 1 ->
Vertex 5: 0 -> 3 -> 2 -> 6 -> 4 -> 1 ->
Vertex 6: 0 -> 3 -> 5 -> 2 -> 4 -> 1 ->
我创建的代码没有正确计算链接数并输出以下内容:
Vertex 0: 2
Vertex 1: 0
Vertex 2: 0
Vertex 3: 1
Vertex 4: 2
Vertex 5: 0
Vertex 6: 2
而此示例的链接数应如下所示:
Vertex 0: 3
Vertex 1: 5
Vertex 2: 4
Vertex 3: 3
Vertex 4: 5
Vertex 5: 3
Vertex 6: 4
我想我可能错过了代码中到下一个节点的切换?我怎样才能解决这个问题?
图结构:
typedef struct graph {
int numberV;
int numberE;
struct vertex **adjList;
} GraphT;
typedef struct vertex {
int vertex;
struct vertex *next;
} VertexT;
计数代码:
int countIncomingLinks(GraphT *graph, int vertex) {
int count = 0;
GraphT *current = graph;
for (int i = 0; i < graph->numberV; i++) {
if (current->adjList[i]->vertex == vertex) {
count++;
}
// current = current->adjList[i]->next;
}
return count;
}
int main() {
...
int incoming[vertices];
for (int j = 0; j < vertices; j++) {
incoming[j] = countIncomingLinks(graph, j);
}
for (int j = 0; j < vertices; j++) {
printf("Vertex %d: %d\n", j, incoming[j]);
}
...
}
解决方案
countIncomingLinks
包含一个循环遍历i
图中顶点的索引。
每个顶点包含一个顶点列表,它具有出边。您需要另一个循环,对于第一个循环迭代的每个顶点,迭代该顶点的出边,并且对于指向目标顶点的每个出边,将计数加 1。
推荐阅读
- c - 如何仅使用指针创建动态矩阵结构?
- r - 在r中将列表项输出到csv时设置正确的列名
- dart - 如何从字符串创建 Dart 函数?
- spreadsheet - 电子表格脚本 IFTTT
- java - 如何使用 Selenium Java 在文本框中验证转换后的文本
- angularjs - 为什么 angular.forEach 会被跳过,就好像它不是在做异步一样?
- python - 如果列值等于 NaN 或零,我该如何计算?
- php - 在 Laravel eloquent 中使用中间关系过滤数据透视表数据
- java - java - 如何在java中正确设置csv文件列格式?
- cobol - 文件辅助中的字帖错位