title: How to find the distance between two nodes using BFS?
body: <p>I wrote this code of BFS in c++ using wikipedia's pseudocode.
  The function takes two parameters s,t. Where s is the source node and t is the target, if the target is fount, the the search return the target itself, or else it return -1.
  Here is my code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;deque&gt;
  #include &lt;vector&gt;
  
  using namespace std;
  
  struct vertex{
  vector&lt;int&gt; edges;
  bool visited;
  };
  
  int dist = 0;
  
  int BFS(vertex Graph[],int v,int target){
  deque&lt;int&gt; Q;
  Q.push_front(v);
  Graph[v].visited = true;
      while(!Q.empty()){
          int t = Q.back();
          Q.pop_back();
              if(t == target){
                  return t;
              }
              for(unsigned int i = 0;i &lt; Graph[t].edges.size();i++){
                  int u = Graph[t].edges[i];
                  if(!Graph[u].visited){
                      Graph[u].visited = true;
                      Q.push_front(u);
                  }
              }
      }
      return -1;
  } 
  
  int main(){
  int n;
  cin &gt;&gt; n;
  vertex Graph[n];
  int k;
  cin &gt;&gt; k;
  for(int i = 0;i &lt; k; i++){
      int a,b;
      cin &gt;&gt; a &gt;&gt; b;
      a--;
      b--;
      Graph[a].edges.push_back(b);
      Graph[b].edges.push_back(a);
  }
  
  for(int i = 0;i &lt; n; i++){
      Graph[i].visited = false;
  }
  
  int s,t;
  cin &gt;&gt; s &gt;&gt; t;
  
  cout &lt;&lt; BFS(Graph,s,t);
  
    }
  </code></pre>
  
  <p>I read this in wikipedia : </p>
  
  <blockquote>
    <p>Breadth-first search can be used to solve many problems in graph theory, for example:<br/>
    Finding the shortest path between two nodes u and v (with path length measured by number > > of edges)</p>
  </blockquote>
  
  <p>How do i change my function BFS to return the shortest path from s to t and return -1 if no path exists?</p>