From 43706105bbb774fdeccc6347111d90c0ff6c54ba Mon Sep 17 00:00:00 2001 From: jf-home Date: Sat, 26 Apr 2025 15:12:43 +0800 Subject: [PATCH] =?UTF-8?q?graph=E7=9A=84=E8=BF=AD=E4=BB=A3=E5=99=A8bfs?= =?UTF-8?q?=E9=81=8D=E5=8E=86=E6=A8=A1=E5=BC=8F=E8=B0=83=E8=AF=95=E9=80=9A?= =?UTF-8?q?=E8=BF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/graph.c | 38 +++++++++++++++++--------------------- test/test_graph.c | 12 +++++------- 2 files changed, 22 insertions(+), 28 deletions(-) diff --git a/src/graph.c b/src/graph.c index b8b1ab7..47e0222 100644 --- a/src/graph.c +++ b/src/graph.c @@ -855,6 +855,20 @@ const void *graph_iter_next(struct _iterator *iter) queue_t queue = self->queue; + if (queue->empty(queue)) + { + cur_node = self->_head->next; + while (cur_node != NULL) + { + if(cur_node->visited != true) + { + queue->push(queue, &cur_node); + break; + } + cur_node = cur_node->next; + } + } + if (!queue->empty(queue) && node != NULL) { queue->pop(queue, &node); @@ -868,33 +882,15 @@ const void *graph_iter_next(struct _iterator *iter) { queue->push(queue, &target); - self->print_obj(node->obj); - printf(" -> "); - self->print_obj(target->obj); + // self->print_obj(node->obj); + // printf(" -> "); + // self->print_obj(target->obj); } cur_edge = cur_edge->next; } cur_node = node; } - else - { - // if queue is empty, find next unvisited node - cur_node = self->_head->next; - while (cur_node != NULL) - { - if(cur_node->visited != true) - { - break; - } - cur_node = cur_node->next; - } - if(cur_node != NULL) - { - queue->push(queue, &cur_node); - iter->_cur_node = cur_node; - } - } iter->_cur_node = cur_node; obj = cur_node->obj; diff --git a/test/test_graph.c b/test/test_graph.c index 97bcd8a..3df66f4 100644 --- a/test/test_graph.c +++ b/test/test_graph.c @@ -141,25 +141,23 @@ void test_graph_iter(void) // graph->print(graph); // test add_edge - TEST_ASSERT_TRUE(graph->add_edge(graph, &data[0], &data[5], 12)); + TEST_ASSERT_TRUE(graph->add_edge(graph, &data[0], &data[1], 12)); TEST_ASSERT_TRUE(graph->add_edge(graph, &data[0], &data[2], 13)); TEST_ASSERT_TRUE(graph->add_edge(graph, &data[1], &data[3], 24)); TEST_ASSERT_TRUE(graph->add_edge(graph, &data[5], &data[6], 67)); + + TEST_ASSERT_TRUE(graph->add_edge(graph, &data[7], &data[6], 24)); + TEST_ASSERT_TRUE(graph->add_edge(graph, &data[9], &data[2], 67)); TEST_ASSERT_FALSE(graph->add_edge(graph, &temp, &data[1], 0)); graph->print(graph); - printf("test iter_vertex: \n"); iterator_t iter_vertex = graph->iter(graph, GRAPH_BFS, &data[0]); TEST_ASSERT_NOT_NULL(iter_vertex); - - printf("start\n"); while(iter_vertex->hasnext(iter_vertex)) { - printf("next : "); temp = *(int *)iter_vertex->next(iter_vertex); - printf("temp = %d\n", temp); + graph->print_obj(&temp); } - printf("end\n"); graph_free(&graph); TEST_ASSERT_NULL(graph);