Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://onlinegdb.com/ZXyYHQYxb
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #define MAX 100
- int adj[MAX][MAX]={0}, queue[MAX], parent[MAX];
- bool visited[MAX];
- int front = 0, rear = 0;
- void addEdge(int u, int v){
- adj[u][v]=adj[v][u]=1;
- }
- bool bfs(int start, int end, int n){
- for(int i=0;i<n;i++){
- visited[i] = false;
- parent[i] = -1;
- }
- queue[rear++] = start;
- visited[start] = true;
- while(front<rear){
- int curr = queue[front++];
- if (curr == end) return true;
- for(int i=0;i<n;i++){
- if(adj[curr][i] && !visited[i]){
- queue[rear++]=i;
- visited[i]=true;
- parent[i]=curr;
- }
- }
- }
- return false;
- }
- void printPath(int start, int end){
- if(end==-1) return;
- printPath(start,parent[end]);
- printf("%d ",end);
- }
- int main(){
- int n,m,u,v,start,end;
- printf("Enter the no of nodes: ");
- scanf("%d",&n);
- printf("Enter the no. of edges: ");
- scanf("%d",&m);
- printf("Enter the edge pairs:\n");
- for(int i=0;i<m;i++){
- scanf("%d %d",&u,&v);
- addEdge(u,v);
- }
- printf("Enter the start and end path: ");
- scanf("%d %d",&start,&end);
- if(bfs(start,end,n)){
- int length = 0;
- for(int i=end;i!=-1;i=parent[i]) length++;
- printf("Shortest path length: %d\nPath: ",length-1);
- printPath(start,end);
- }else{
- printf("No path found");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement