GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

What's wrong with this code for BFS? Getting wrong output..

#include<stdio.h>

int graph[10][10];

void bfs(int s, int v)
{
    
    int q[10];
    int front=0;int rear =0;
    int visited[10];
    int i, j;
    
    for(i=0;i<v;i++)
    {
    visited[i] = 0;
    }
    
    visited[s]=1;
    
    q[rear++] = s;
        
    while(front<=rear)
    {
        s = q[front];
        rear--;
        printf("%d",s);
        
        for(j=1;j<=v;j++)
        {
            if(graph[s][j]==1 && visited[j]!=1)
            {
                visited[j]=1;
                q[rear++] = j;
             } 
        }
    }
    
}

 

 

int main()
{
    int V,E;
    int m , n;
    int i,j;
    printf("Enter the number of vertices and Edges");
    scanf("%d%d",&V,&E);
    int graph[V][V];
    
    
    for(i=0;i<V;i++)
    {
        for(j=0;j<V;j++)
        {
            graph[i][j]=0;
        }
    }
    
    printf("Enter the elements");
    for(i=0;i<E;i++)
    {
            scanf("%d%d",&m,&n);
            graph[m][n] = 1;
    }
    
    bfs(1,V);
    
}

 

asked Jun 30, 2015 by sarab
edited Jun 30, 2015 by sarab

Also the indices which you are using to initialize graph[][] are 1 less than the indices used to initialize visited array. There is a mix up of indices. Just check it out. Also rear-- should be front++

2 Answers

s = q[front];
        rear--;

shouldn't this be front++?

answered Jun 30, 2015 by jayasurya_j

Not working.... :\

There are some mistakes.

  1. You have declared graph[v][v] array in your function also, remove it from there.
  2. Use front++ instead of rear--.
  3. Loop in bfs function should go from 0 to n-1, not from 1 to n.

And remember one thing that you are taking vertex from 0 to n-1.

Here is the right code with above changes.

#include<stdio.h>

int graph[10][10];

void bfs(int s, int v)
{
    
    int q[10];
    int front=0;int rear =0;
    int visited[10];
    int i, j;
    
    for(i=0;i<v;i++)
    	visited[i] = 0;
    
    visited[s]=1;
    
    q[rear++] = s;
        
    while(front<rear)
    {
        s = q[front++];
        printf("%d",s);
        
        for(j=0;j<v;j++)
        {
            if(graph[s][j]==1 && visited[j]!=1)
			{
                visited[j]=1;
                q[rear++] = j;
            } 
		}
    }
    
}

 

 

int main()
{
    int V,E;
    int m , n;
    int i,j;
    printf("Enter the number of vertices and Edges\n");
    scanf("%d%d",&V,&E);
    
    for(i=0;i<V;i++)
    {
        for(j=0;j<V;j++)
        {
            graph[i][j]=0;
        }
    }
    
    printf("Enter the elements\n");
    for(i=0;i<E;i++)
    {
            scanf("%d%d",&m,&n);
            graph[m][n] = 1;
    }
    
    bfs(1,V);
    
}

 

answered Nov 2, 2015 by gccode
...