- 모든 지점에서 다른 모든 지점까지의 최단 경로를 모두 구하는 알고리즘
- DP로 분류
- 시간 복잡도 O(N^3)
- 문제의 범위가 작은 경우 구현이 간단한 다익스트라 알고리즘보다 플로이드 워셜 알고리즘을 이용하는 것이 유리하다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#define INF 1e9
using namespace std;
int n, m;
int graph[501][501];
int main(int argc, const char * argv[]) {
cin >> n >> m;
for (int i = 0; i < 501; i++) {
fill(graph[i], graph[i] + 501, INF);
}
for(int i=1;i<=m;i++) {
for(int j=1;j<=m;j++) {
if(i==j) graph[i][j] = 0;
}
}
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
graph[a][b] = c;
}
for(int k=1;k<=n;k++) {
for(int a=1;a<=n;a++) {
for(int b=1;b<=n;b++) {
graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b]);
}
}
}
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
if (graph[a][b] == INF) {
cout << "INFINITY" << ' ';
}
else {
cout << graph[a][b] << ' ';
}
}
cout << endl;
}
}