我假设这里的图是顶点和边的集合。为此,您需要一个指向结构的指针数组。这是图的邻接表表示。这些结构至少有一个值,即节点号和指向另一个结构的指针。在将新节点插入图形时,只需转到数组的适当索引并在开始时推送节点。这是插入的 O(1) 时间。我的实现可能会帮助您了解它的实际工作原理。如果你在 C 方面有很好的技能,那么理解代码不会花费太多时间。
// Graph implementation by adjacency list
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1000
typedef struct node{
int number;
struct node * next;
} Node;
// U is starting node, V is ending node
void addNode (Node *G[], int U, int V, int is_directed)
{
Node * newnode = (Node *)malloc(sizeof(Node));
newnode->number = V;
newnode->next = G[U];
G[U] = newnode;
// 0 for directed, 1 for undirected
if (is_directed)
{
Node * newnode = (Node *)malloc(sizeof(Node));
newnode->number = U;
newnode->next = G[V];
G[V] = newnode;
}
}
void printgraph(Node *G[], int num_nodes)
{
int I;
for (I=0; I<=num_nodes; I++)
{
Node *dum = G[I];
printf("%d : ",I);
while (dum != NULL)
{
printf("%d, ",dum->number);
dum =dum->next;
}
printf("\n");
}
}
void dfs (Node *G[], int num_nodes, int start_node)
{
int stack[MAX_SIZE];
int color[num_nodes+1];
memset (color, 0, sizeof(color));
int top = -1;
stack[top+1] = start_node;
top++;
while (top != -1)
{
int current = stack[top];
printf("%d ",current);
top--;
Node *tmp = G[current];
while (tmp != NULL)
{
if (color[tmp->number] == 0)
{
stack[top+1] = tmp->number;
top++;
color[tmp->number] = 1;
}
tmp = tmp->next;
}
}
}
void bfs (Node *G[], int num_nodes, int start_node)
{
int queue[MAX_SIZE];
int color[num_nodes+1];
memset (color, 0, sizeof (color));
int front=-1, rear=-1;
queue[rear+1] = start_node;
rear++;printf("\n\n");
while (front != rear)
{
front++;
int current = queue[front];
printf("%d ",current);
Node *tmp = G[current];
while (tmp != NULL)
{
if (color[tmp->number] == 0)
{
queue[rear+1] = tmp->number;
rear++;
color[tmp->number] = 1;
}
tmp = tmp->next;
}
}
}
int main(int argc, char **argv)
{
int num_nodes;
// For Demo take num_nodes = 4
scanf("%d",&num_nodes);
Node *G[num_nodes+1];
int I;
for (I=0; I<num_nodes+1 ;I++ )
G[I] = NULL;
addNode (G, 0, 2, 0);
addNode (G, 0, 1, 0);
addNode (G, 1, 3, 0);
addNode (G, 2, 4, 0);
addNode (G, 2, 1, 0);
printgraph( G, num_nodes);
printf("DFS on graph\n");
dfs(G, num_nodes, 0);
printf("\n\nBFS on graph\n");
bfs(G, num_nodes, 0);
return 0;
}