graph_bfs还存在逻辑问题

This commit is contained in:
建峰 2024-09-09 10:25:58 +08:00
parent 4c68d1abdc
commit 04f8c116f3
3 changed files with 24 additions and 12 deletions

View File

@ -16,6 +16,7 @@
struct _graph_node { struct _graph_node {
void *obj; void *obj;
uint32_t **edge; uint32_t **edge;
uint8_t *visited;
}; };
struct _graph { struct _graph {

View File

@ -125,6 +125,8 @@ static bool graph_from_matrix(struct _graph *self, void *obj, uint32_t *edges, u
self->_head->edge[i][j] = edges[i * size + j]; self->_head->edge[i][j] = edges[i * size + j];
} }
} }
self->_size = size;
return true; return true;
} }
@ -142,21 +144,20 @@ static bool graph_bfs(struct _graph *self, uint32_t idx)
queue_t queue = queue_new(); queue_t queue = queue_new();
queue_init(queue, sizeof(int)); queue_init(queue, sizeof(int));
#if 0
queue->push(queue, &node); queue->push(queue, &idx);
while (!queue->empty(queue)) while (!queue->empty(queue))
{ {
queue->pop(queue, &node); queue->pop(queue, &idx);
if (node->left != NULL) for(uint32_t i = 0; i < self->_size; i++)
{ {
queue->push(queue, &node->left); if(self->_head->edge[idx][i] == 1 && self->_head->visited[i] == 0)
} {
if (node->right != NULL) queue->push(queue, &i);
{ self->_head->visited[i] == 1;
queue->push(queue, &node->right); }
} }
} }
#endif
queue_free(&queue); queue_free(&queue);
return true; return true;
} }
@ -243,10 +244,18 @@ graph_t graph_new2(uint32_t obj_size, uint32_t capacity)
} }
} }
graph->_head->visited = (uint8_t *)calloc(1, graph->_capacity * sizeof(uint8_t));
if(graph->_head->visited == NULL)
{
goto done5;
}
// init graph // init graph
graph->init(graph); graph->init(graph);
return graph; return graph;
done5:
done4: done4:
for(uint32_t j = 0; j < i; j++) for(uint32_t j = 0; j < i; j++)
{ {

View File

@ -34,7 +34,7 @@ void test_graph_from_matrix(void)
{ {
// const uint32_t size = 10; // const uint32_t size = 10;
#define size 5 #define size 5
int vertexs[size] = {1,2,3,4,5}; int vertexs[size] = {0, 1, 2, 3, 4};
int matrix[size * size] = { int matrix[size * size] = {
0, 1, 0, 0, 0, 0, 1, 0, 0, 0,
1, 0, 1, 0, 0, 1, 0, 1, 0, 0,
@ -49,7 +49,9 @@ void test_graph_from_matrix(void)
// graph->print(graph); // graph->print(graph);
graph->from_matrix(graph, vertexs, matrix, size); graph->from_matrix(graph, vertexs, matrix, size);
// graph->print(graph); graph->print(graph);
graph->bfs(graph, 1);
graph_free(&graph); graph_free(&graph);
TEST_ASSERT_NULL(graph); TEST_ASSERT_NULL(graph);