Skip to content

Instantly share code, notes, and snippets.

@mingtsay
Created September 1, 2012 10:02
Show Gist options
  • Save mingtsay/3568657 to your computer and use it in GitHub Desktop.
Save mingtsay/3568657 to your computer and use it in GitHub Desktop.
graph
#include <stdio.h>
#include <stdlib.h>
int *queue_new(int size)
{
int *queue = (int *)malloc(sizeof(int) * size);
int i;
for(i = 0; i < size; ++i)
{
queue[i] = EOF;
}
return queue;
}
int queue_pop(int *queue, int size)
{
int i, pop;
pop = queue[0];
if(pop == EOF) return EOF;
for(i = 0; i < size && queue[i] != EOF; ++i)
{
if(i == size - 1)
{
queue[i] = EOF;
}
else
{
queue[i] = queue[i + 1];
}
}
return pop;
}
int queue_push(int *queue, int size, int value)
{
int i;
for(i = 0; i < size; ++i)
{
if(queue[i] == EOF)
{
queue[i] = value;
return 1;
}
}
return 0;
}
int queue_empty(int *queue)
{
return queue[0] == EOF;
}
void BFS(int **graphic, int n, int node)
{
int *walked = (int *)calloc(n, sizeof(int));
int *queue = queue_new(n);
int i;
printf("%d", node);
walked[node - 1] = 1;
queue_push(queue, n, node);
while(!queue_empty(queue))
{
node = queue_pop(queue, n);
for(i = 0; i < n; ++i)
{
if(graphic[node - 1 + i * n] && !walked[i])
{
printf(", %d", i + 1);
walked[i] = 1;
queue_push(queue, n, i + 1);
}
}
}
}
void DFS_walk(int **graphic, int n, int node, int *walked)
{
int i;
for(i = 0; i < n; ++i)
{
if(graphic[node - 1 + i * n] && !walked[i])
{
printf(", %d", i + 1);
walked[i] = 1;
DFS_walk(graphic, n, i + 1, walked);
}
}
}
void DFS(int **graphic, int n, int node)
{
int *walked = (int *)calloc(n, sizeof(int));
printf("%d", node);
walked[node - 1] = 1;
DFS_walk(graphic, n, node, walked);
}
int main()
{/*
int graphic[8][8] =
{
{1, 1, 0, 1, 0, 1, 0, 0},
{1, 1, 1, 0, 0, 0, 0, 0},
{0, 1, 1, 0, 1, 0, 0, 1},
{1, 0, 0, 1, 1, 1, 0, 0},
{0, 0, 1, 1, 1, 0, 1, 0},
{1, 0, 0, 1, 0, 1, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 1},
{0, 0, 1, 0, 0, 0, 1, 1}
}
; // map
int n = 8; // number of nodes
*/
int graphic[5][5] =
{
{1, 0, 0, 0, 1},
{0, 1, 0, 0, 1},
{0, 0, 1, 0, 0},
{1, 0, 1, 1, 1},
{0, 0, 0, 0, 1}
}
; // map
int n = 5; // number of nodes
printf("DFS: ");
DFS((int **)graphic, n, 5);
printf("\n");
printf("BFS: ");
BFS((int **)graphic, n, 5);
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment