title: Calculating shortest path with BFS in R
body: <p>I'm working with R to make a breadth-first search of a network.  Here is the code I have so far:</p>
  
  <pre><code>shortestPath &lt;- function(v1,v2) {
    q &lt;- rep(0, 3931)
    head &lt;- 1
    head2 &lt;- 0
    tail &lt;- 1
    v1$distance &lt;- 0
    q[tail] &lt;- v1
    while(head &lt;= tail) {
      v &lt;- q[head]
      head &lt;- head + 1
      if(v==v2) {
        return(v$distance)
        }
      vEdges &lt;- get.neighborhood(net, v)
      m &lt;- rep(0,3931)
      m[head2] &lt;- v
      head2 &lt;- head2 + 1
      for(n in vEdges) {
      if(!(n %in% m)) {
        n$distance &lt;- v$distance + 1
        m[head2] &lt;- n
        head2 &lt;- head2 + 1
        tail &lt;- tail + 1
        q[tail] &lt;- n
        }
      }
    }
  }
  </code></pre>
  
  <p>I'm not quite sure what is going on with it.  It just gets stuck in the while loop infinitely.  The network I'm dealing with works and is fully connected.  I think there is just a minor problem with this that I'm not seeing, if anyone could put me in the right direction toward fixing this, that would be great.  I'm probably not as experienced as a typical R user.</p>
  
  <p>Thanks.</p>