Finding the shortest path of all nodes from a given node using BFS

when i increase or decrease the INF value it outputs the result Unexpectedly .. I think the INF should not influence the result. the length of each edge is 6 for input 1 4 2 1 2 1 3 1 output 6 6 -1 when i change INF to 1e8 output 0 0 0

 #include<iostream>
 #include<vector>
 #include<queue>
 #include<cstring>

 using namespace std;

 #define MAX 2000
  #define INF 1000000

 vector<int> adj[MAX];
 int d[MAX];
  bool visited[MAX];

 void initialise(){
   for(int i=0;i<=MAX;i++){
  visited[i]=false;
   }
  }

  void shortestPathBfs(int start){

  queue<int> q;
   q.push(start);
     visited[start]=true;
     d[start]=0;

  while(!q.empty()){
      int p=q.front();
       q.pop();
      for(int i=0;i<adj[p].size();i++){
           int v=adj[p][i];
            if(!visited[v] && d[v]>d[p]+6){
                d[v]=d[p]+6;
                q.push(v);
               visited[v]=true;
            }
        }
       }
      }

         int main(){
         int T,N,M,S,x,y;
            cin>>T;
          while(T--){
        cin>>N>>M;
      for(int i=0;i<M;i++){
         cin>>x>>y;
          adj[x].push_back(y);
          adj[y].push_back(x);
      }
      cin>>S;

       initialise();
         memset(d,INF,sizeof(d));
         shortestPathBfs(S);

   for(int i = 1; i <=N; i++) {
        if(i == S)
            continue;
        if(d[i] >= INF)
              cout<<"-1"<<" ";
        else
            cout<<d[i]<<" ";
          }
       }

      }

      

+3


source to share


1 answer


The problem is

memset(d,INF,sizeof(d));

      



memset()

fills the memory with only a byte. Here it will complete filling the array with the least significant byte of the value int

INF

. To fix this, create an explicit loop for

or use std::fill()

.

+1


source







All Articles