Skip to content

Instantly share code, notes, and snippets.

@slashvar
Created September 20, 2017 09:26
Show Gist options
  • Save slashvar/0c38c8526bf458b65d7fe8da6ad25337 to your computer and use it in GitHub Desktop.
Save slashvar/0c38c8526bf458b65d7fe8da6ad25337 to your computer and use it in GitHub Desktop.
Recursive example of a BFS in C
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
struct queue {
size_t cap, start, size;
int store[0];
};
struct queue* new_queue(size_t cap)
{
struct queue *q = malloc(sizeof (struct queue) + cap * sizeof (int));
q->cap = cap;
q->start = q->size = 0;
return q;
}
void push(struct queue *q, int x)
{
assert(q->size < q->cap);
q->store[(q->start + q->size) % q->cap] = x;
q->size += 1;
}
int pop(struct queue *q)
{
assert(q->size);
int x = q->store[q->start];
q->start += 1;
q->size -= 1;
return x;
}
int edges[4][4] = {
{0, 1, 1, 0},
{1, 0, 0, 1},
{1, 0, 0, 0},
{0, 1, 0, 0}
};
int vertices = 4;
int set[4] = {0};
int recbfs(int i, struct queue *q)
{
printf("%d ", i); // display vertices as soon as they are visited
for (int j = 0; j < vertices; j++) {
if (i != j && edges[i][j] && set[j] == 0) {
set[j] = 1;
push(q, j);
}
}
if (q->size == 0)
return 1;
int next = pop(q);
return recbfs(next, q);
}
int main()
{
struct queue *q = new_queue(vertices);
set[0] = 1;
recbfs(0, q);
free(q);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment