Help me in solving CHEFSERVER problem

My issue

Why am I getting runtime error.?

My code

class solution {
public:
    int getMinimumServers(int n, vector<pair<int, int>>ser){
        // Complete the code
        vector<int>Graph[n+1];
        for(auto p:ser)
        {
            Graph[p.first].push_back(p.second);
            Graph[p.second].push_back(p.first);
        }
        queue<int>pend;
        pend.push(1);
        int fine=-1;
        vector<bool>visited(n+1,false);
        int ans=0;
        while(!pend.empty())
        {
            int ft=pend.front();
            pend.pop();
          
                for(int adj:Graph[ft])
                {
                    if(adj==n) return 1+ans;
                    if(!visited[adj]) pend.push(adj);
                }
           
            ans++;
        }
        return -1;
    }
    
  
};

Learning course: Graphs
Problem Link: Chef Shortest Route Practice Problem in Graphs - CodeChef

@ravan_monu
U have to mark the visited array as well .
plzz refer the following for better understanding

class solution {
public:
    int getMinimumServers(int n, vector<pair<int, int> > serverConnections){
      int m = serverConnections.size();
      int dis[n + 1];
      vector<int> g[n + 1];
      for(int i = 1; i <= n; i++)
         dis[i] = 1e9;
     
      for(auto e: serverConnections){
         int a = e.first, b = e.second;
        
         g[a].push_back(b);
         g[b].push_back(a);
      }
     
      queue<int> q;
      q.push(1);
      dis[1] = 0;
      int par[n + 1];
      while(!q.empty()){
         int v = q.front();
         q.pop();
         if(v == n) break;
     
         for(int adj : g[v]){
             if(1 + dis[v] < dis[adj]){
                dis[adj] = 1 + dis[v];
                par[adj] = v;
                q.push(adj);
             }
         }
      }
     
      if(dis[n] == (int)1e9)
         return -1;
     
      return 1 + dis[n];
    }
};
1 Like