#include <stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }*front=NULL,*rear=NULL; void enq(int key) { struct node *t; t=(struct node*)malloc(sizeof(struct node)); if(t==NULL) printf("queue is full"); else { t->data=key; t->next=NULL; if(front==NULL) front=rear=t; else { rear->next=t; rear=t; } } } int deq() { int x=-1; struct node *t; if(front==NULL) { printf("queue is empty"); } else { x=front->data; t=front; front=front->next; free(t); } return x; } int qempty() { return front==NULL; } void BFS(int G[7][7],int s,int n) { int i=s,j; int vis[7]={0}; vis[i]=1; printf("%d ",i); enq(i); while(!qempty()) { i=deq(); for(int j=1;j<n;j++) { if(G[i][j]==1 && vis[j]==0) { vis[j]=1; printf("%d ",j); enq(j); } } } } int main() { int G[7][7]={{0,0,0,0,0,0,0}, {0,0,1,1,0,0,0}, {0,1,0,0,1,0,0}, {0,1,0,0,1,0,0}, {0,0,1,1,0,1,1}, {0,0,0,0,1,0,0}, {0,0,0,0,1,0,0}}; BFS(G,4,7); }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter