title: Dijsktra Path Finding
body: <p>I know there are lots of questions based on this algorithm. I am beginner and I was given an assignment on path finding. I wrote some code which finds shortest path between two nodes. In my code when I put in Node as 0 , then it works fine, but not on other nodes. What's the problem ??</p>
  
  <pre><code>#include&lt;iostream&gt;
  using namespace std;
  
  int main(){
      int matrix[5][5];
      int visited[5];
      int distance[5];
      int min , nextnode=0;
  
      for(int i=0;i&lt;5;i++){
          visited[i]=0;
          for(int j=0;j&lt;5;j++){
              cin&gt;&gt;matrix[i][j];
              if(matrix[i][j] == 0)
                  matrix[i][j] = 999;     
          }   
      }
      int inNode,traceBack[5],pathNode;
      cout&lt;&lt;"Enter Initial Node: ";
      cin&gt;&gt;inNode;
      cout&lt;&lt;"Enter Path Node: ";
      cin&gt;&gt;pathNode;
      distance[inNode] = 0;
      visited[inNode] =1;
      for(int i=0 ; i&lt; 5 ; i++){
          distance[i]=matrix[inNode][i];
  
      }
  
      for(int i=0;i&lt;5;i++){
          min=999;
          for(int j=0;j&lt;5;j++){
              if(min&gt;distance[j] &amp;&amp; visited[j] != 1){
                  min=distance[j];
                  nextnode=j;
              }
  
          }
          visited[nextnode] = 1;
          for(int c=0;c&lt;5;c++){
              if(visited[c]!=1){
                  if(min+matrix[nextnode][c] &lt; distance[c]){
                      distance[c] = min + matrix[nextnode][c];
                      traceBack[c] = nextnode;                    
                  }
              }
          }
      }
  
      //  cout&lt;&lt;"-&gt;"&lt;&lt;traceBack[i];
      int j;
      cout&lt;&lt;"Path = "&lt;&lt;pathNode;
      j=pathNode;
      do{
          j=traceBack[j];
          cout&lt;&lt;"&lt;-"&lt;&lt;j;
      }while(j!=inNode);  
      return 0;
  }
  </code></pre>