Advertisement
GamerBhai02

9. BFS Shortest Connection b/w users

Jan 11th, 2025 (edited)
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.53 KB | Source Code | 0 0
  1. https://onlinegdb.com/ZXyYHQYxb
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdbool.h>
  5. #define MAX 100
  6. int adj[MAX][MAX]={0}, queue[MAX], parent[MAX];
  7. bool visited[MAX];
  8. int front = 0, rear = 0;
  9. void addEdge(int u, int v){
  10.     adj[u][v]=adj[v][u]=1;
  11. }
  12. bool bfs(int start, int end, int n){
  13.     for(int i=0;i<n;i++){
  14.         visited[i] = false;
  15.         parent[i] = -1;
  16.     }
  17.     queue[rear++] = start;
  18.     visited[start] = true;
  19.     while(front<rear){
  20.         int curr = queue[front++];
  21.         if (curr == end) return true;
  22.         for(int i=0;i<n;i++){
  23.             if(adj[curr][i] && !visited[i]){
  24.                 queue[rear++]=i;
  25.                 visited[i]=true;
  26.                 parent[i]=curr;
  27.                
  28.             }
  29.         }
  30.     }
  31.     return false;
  32. }
  33. void printPath(int start, int end){
  34.     if(end==-1) return;
  35.     printPath(start,parent[end]);
  36.     printf("%d ",end);
  37. }
  38. int main(){
  39.     int n,m,u,v,start,end;
  40.     printf("Enter the no of nodes: ");
  41.     scanf("%d",&n);
  42.     printf("Enter the no. of edges: ");
  43.     scanf("%d",&m);
  44.     printf("Enter the edge pairs:\n");
  45.     for(int i=0;i<m;i++){
  46.         scanf("%d %d",&u,&v);
  47.         addEdge(u,v);
  48.     }
  49.     printf("Enter the start and end path: ");
  50.     scanf("%d %d",&start,&end);
  51.     if(bfs(start,end,n)){
  52.         int length = 0;
  53.         for(int i=end;i!=-1;i=parent[i]) length++;
  54.         printf("Shortest path length: %d\nPath: ",length-1);
  55.         printPath(start,end);
  56.     }else{
  57.         printf("No path found");
  58.     }
  59.     return 0;
  60. }
Tags: bfs
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement