我正在尝试删除图中出现的多条边。图中的每个顶点可以具有到相同目的地的多个传出边。像这样的(这是邻接列表)。例如,从(3 --> 2)有2个连接。括号中的数字显示每条边的距离、成本和时间。在这种情况下,我想删除所有时间较长的边。例如第一线路第二连接,这需要45小时。
### 3 -> 2 (50-300-40) ---> 2 (55-450-45) ---> 4 (45-450-45) ---> 4 (75-600-60) ---> 1 (40-450-40) ---> 1 (85-750-90) ---> NULL
### 2 -> 1 (50-450-45) ---> 3 (45-300-30) ---> 4 (80-700-80) ---> NULL
### 4 -> 2 (55-535-60) ---> 3 (75-545-65) ---> 4 (20-200-20) ---> NULL
void delete_edge(graph *g, int source_no, int dest_no) {
// Find the source vertex
node *source_vertex = &g->heads[source_no];
list_node *current = source_vertex->head;
list_node *prev = NULL;
// Create a new adjacency list
list_node *new_head = NULL;
list_node *new_tail = NULL;
// Traverse the adjacency list of the source vertex
while (current != NULL) {
if (current->index_of_item == dest_no) {
// Found the edge to delete, skip it
list_node *temp = current;
current = current->next;
free(temp);
if (prev != NULL) {
prev->next = current;
} else {
source_vertex->head = current;
}
} else {
// Add the current edge to the new adjacency list
if (new_head == NULL) {
new_head = current;
new_tail = current;
} else {
new_tail->next = current;
new_tail = current;
}
prev = current;
current = current->next;
}
}
// Set the next pointer of the new tail to NULL
if (new_tail != NULL) {
new_tail->next = NULL;
}
}
void bfs_delte_version(graph *g) {
// Initialize the color of all vertices as White
for (int i = 0; i < g->number_of_vertices; i++) {
g->heads[i].color = White;
}
// Start BFS from the first node (source)
node *source = &g->heads[0];
source->color = Gray;
queue *q = make_queue();
enqueue(q, source);
while (!is_empty_queue(q)) {
queue_node *u = dequeue(q);
list_node *temp = u->n->head;
while (temp != NULL) {
if (g->heads[temp->index_of_item].color == White) {
g->heads[temp->index_of_item].color = Gray;
enqueue(q, &g->heads[temp->index_of_item]);
} else {
// Delete multiple occurring edges
delete_edge(g, u->n->data, temp->index_of_item);
}
temp = temp->next;
}
u->n->color = Black;
printf("%d\n", u->n->data);
}
}
我已经改变了我的策略,使用BFS遍历图,然后删除边,但我不知道为什么它不起作用。当在单个边上调用时,它不会改变图,当在BFS遍历上调用时,我得到分割错误。我将感激你的帮助
1条答案
按热度按时间wd2eg0qa1#
您尚未实现else分支