Thursday, December 1, 2011

Program for Breadth First Search in a graph using C

#include

#define MAX 10

int n;
int adj[MAX][MAX
];
int visited[MAX];
void readmatrix()
{
    int i,j;
    printf("\nEnter the number of Vertices in the Graph : ");
    scanf("%d",&n);
    printf("\nEnter the Adjacency Matrix\n\n");
    for (i = 1; i <= n; i++)
        for (j = 1; j<= n; j++)
            scanf("%d",&adj[i][j]);
    for (i = 1; i <= n; i++)
        visited[i] = 0;
}

void bfs(int source)
{
    int queue[MAX];
    int i, front, rear, root;
    front = rear = 0;
    visited[source] = 1;
    queue[rear++] = source;
    printf("%d   ",source);
    while (front != rear)
    {
        root = queue[front];
        for (i = 1; i <= n; i++)
            if (adj[root][i] && !visited[i])
            {
                visited[i] = 1;
                queue[rear++] = i;
                printf("%d   ",i);
            }
        front++;
    }
}

int main()
{
    int source;
    printf("\n Program for Breadth First Search for a un-directed Graph");
    readmatrix();
    printf("\nEnter the Source : ");
    scanf("%d",&source);
    printf("\nThe nodes visited in the BFS order is : ");
    bfs(source);
    return 0;
}

3 comments:

  1. I have small question
    is it possible to traverse the tree by passing the input to bfs function as 0(i.e, i want to traverse whole tree start from position 0, because i dont know the data in the node )

    ReplyDelete
  2. simple, nice code

    ReplyDelete