Saturday, February 18, 2017

BFS Algorithm - Implementation with C++

/*
    Bismillahir Rahmamir Rahim
    Implementing BFS algorithm with c++
*/

#include<bits/stdc++.h>
using namespace std;

vector<int>vt[100];
queue<int>q;
int cost[100][100], dis[100], visit[100];

void bfs(int st){
    for(int i=0; i<=100; i++){
        dis[i]=100009, visit[i]=0;
    }
    int p, y, cst;
    dis[st]=0;
    q.push(st);

    while(!q.empty()){
        p=q.front();
        q.pop();
        if(!visit[p]){
            for(int i=0; i<vt[p].size(); i++){
                y=vt[p][i];
                cst=cost[p][y]+dis[p];
                if(cst<dis[y]){
                    dis[y]=cst;
                    q.push(y);
                }
            }
            visit[p]=1;
        }
    }
}

int main(){
    int n1, n2, edge, c, x;
    cin>>edge;
    for(int i=0; i<edge; i++){
        cin>>n1>>n2>>c;
        vt[n1].push_back(n2);
        vt[n2].push_back(n1);
        cost[n1][n2]=cost[n2][n1]=c;
    }
    bfs(1);
    while(cin>>x) cout<<dis[x]<<endl;
    return 0;
}

No comments:

Post a Comment