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 {
void *obj;
uint32_t **edge;
uint8_t *visited;
};
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->_size = size;
return true;
}
@ -142,21 +144,20 @@ static bool graph_bfs(struct _graph *self, uint32_t idx)
queue_t queue = queue_new();
queue_init(queue, sizeof(int));
#if 0
queue->push(queue, &node);
queue->push(queue, &idx);
while (!queue->empty(queue))
{
queue->pop(queue, &node);
if (node->left != NULL)
queue->pop(queue, &idx);
for(uint32_t i = 0; i < self->_size; i++)
{
queue->push(queue, &node->left);
}
if (node->right != NULL)
if(self->_head->edge[idx][i] == 1 && self->_head->visited[i] == 0)
{
queue->push(queue, &node->right);
queue->push(queue, &i);
self->_head->visited[i] == 1;
}
}
}
#endif
queue_free(&queue);
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
graph->init(graph);
return graph;
done5:
done4:
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;
#define size 5
int vertexs[size] = {1,2,3,4,5};
int vertexs[size] = {0, 1, 2, 3, 4};
int matrix[size * size] = {
0, 1, 0, 0, 0,
1, 0, 1, 0, 0,
@ -49,7 +49,9 @@ void test_graph_from_matrix(void)
// graph->print(graph);
graph->from_matrix(graph, vertexs, matrix, size);
// graph->print(graph);
graph->print(graph);
graph->bfs(graph, 1);
graph_free(&graph);
TEST_ASSERT_NULL(graph);