fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. void shortest_distance(vector<vector<int>>&matrix) {
  6. int n = matrix.size();
  7. for(int i=0;i<n;i++){
  8. matrix[i][i] = 0;
  9. }
  10. for(int k=0;k<n;k++){
  11. for(int i=0;i<n;i++){
  12. if(i==k) continue;
  13. for(int j=0;j<n;j++){
  14. if(i==j or j==k) continue;
  15. if(matrix[i][k] == -1 or matrix[k][j] == -1) continue;
  16. matrix[i][j] = matrix[i][j] == -1 ? matrix[i][k]+matrix[k][j] : min(matrix[i][k]+matrix[k][j],matrix[i][j]);
  17. }
  18. }
  19. }
  20. }
  21.  
  22. int main() {
  23. int V = 4;
  24. vector<vector<int>> matrix(V, vector<int>(V, -1));
  25. matrix[0][1] = 2;
  26. matrix[1][0] = 1;
  27. matrix[1][2] = 3;
  28. matrix[3][0] = 3;
  29. matrix[3][1] = 5;
  30. matrix[3][2] = 4;
  31.  
  32. shortest_distance(matrix);
  33.  
  34. for (auto row : matrix) {
  35. for (auto cell : row) {
  36. cout << cell << " ";
  37. }
  38. cout << endl;
  39. }
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0s 5312KB
stdin
Standard input is empty
stdout
0 2 5 -1 
1 0 3 -1 
-1 -1 0 -1 
3 5 4 0