백준
1. 플로이드 워셜 알고리즘
INF = int(1e9)
n = int(input())
m = int(input())
graph = [[INF] * (n + 1) for _ in range(n + 1)]
for a in range(1, n + 1):
for b in range(1, n + 1):
if a == b:
graph[a][b] = 0
for _ in range(m):
a, b, c = map(int, input().split())
graph[a][b] = min(c, graph[a][b])
for k in range(1, n + 1):
for a in range(1, n + 1):
for b in range(1, n + 1):
graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b])
for a in range(1, n + 1):
for b in range(1, n + 1):
if graph[a][b] == INF:
print(0, end=" ")
else:
print(graph[a][b], end=" ")
print()
2. C++
#include <bits/stdc++.h>
#define INF 1e9
using namespace std;
int n, m;
int graph[501][501];
int main(void) {
cin >> n >> m;
for (int i = 0; i < 501; i++) {
fill(graph[i], graph[i] + 501, INF);
}
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
if (a == b) graph[a][b] = 0;
}
}
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
graph[a][b] = min(c, graph[a][b]);
}
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 << 0 << ' ';
}
else {
cout << graph[a][b] << ' ';
}
}
cout << '\n';
}
}