fork(1) download
  1. #include<iostream>
  2. #include<queue>
  3.  
  4. using namespace std;
  5.  
  6. int n, arr[100][100], par[100], vis[100], ans[100];
  7.  
  8. void bfs(int start, int end){
  9. queue<int> Q;
  10. Q.push(start);
  11. par[start] = -1;vis[start] = 1;
  12. bool found = false;
  13. while(Q.size() > 0){
  14. int v = Q.front();
  15. Q.pop();
  16. if(v == end){
  17. found = true;
  18. break;
  19. }
  20. for(int i = 1;i <= n;i++){
  21. if(arr[v][i] == 0 || vis[i] == 1) continue;
  22. Q.push(i);vis[i] = 1;
  23. par[i] = v;
  24. }
  25. }
  26. if(found == false){
  27. cout << "No Path Found" << endl;return;
  28. }
  29. int curr = end, len = 0;
  30. while(curr != -1){
  31. ans[len++] = curr;
  32. curr = par[curr];
  33. }
  34. for(int i = len-1;i >= 1;i--) cout << ans[i] << " " << ans[i-1] << endl;
  35. }
  36.  
  37. int main(){
  38. n = 5;
  39. arr[1][2] = 1;arr[2][1] = 1;
  40. arr[2][4] = 1;arr[4][2] = 1;
  41. arr[4][5] = 1;arr[5][4] = 1;
  42. arr[3][4] = 1;arr[4][3] = 1;
  43.  
  44. bfs(1, 3);
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
1 2
2 4
4 3