π‘ Info
λ΄μ©
n(2 β€ n β€ 100)κ°μ λμκ° μλ€. κ·Έλ¦¬κ³ ν λμμμ μΆλ°νμ¬ λ€λ₯Έ λμμ λμ°©νλ m(1 β€ m β€ 100,000)κ°μ λ²μ€κ° μλ€. κ° λ²μ€λ ν λ² μ¬μ©ν λ νμν λΉμ©μ΄ μλ€.
λͺ¨λ λμμ μ (A, B)μ λν΄μ λμ Aμμ Bλ‘ κ°λλ° νμν λΉμ©μ μ΅μκ°μ ꡬνλ νλ‘κ·Έλ¨μ μμ±νμμ€.
π₯μ λ ₯ 쑰건
5
14
1 2 2
1 3 3
1 4 1
1 5 10
2 4 2
3 4 1
3 5 1
4 5 3
3 5 10
3 1 8
1 4 2
5 1 7
3 4 2
5 2 4
π€μΆλ ₯ 쑰건
0 2 3 1 4
12 0 15 2 5
8 5 0 1 1
10 7 13 0 3
7 4 10 6 0
μ€μ νμ΄ μκ° : 17λΆ
import java.util.*;
public class Main {
static final int INF = (int) 1e9;
static int n;
static int m;
public static int[][] TD;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
TD = new int[n][n];
for (int i = 0; i < 101; i++) {
Arrays.fill(TD[i], INF);
}
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
if (a == b) TD[a][b] = 0;
}
}
for (int k = 1; k <= n; k++) {
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
TD[a][b] = Math.min(TD[a][b], TD[a][k] + TD[k][b]);
}
}
}
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
if (TD[a][b] == INF) {
System.out.print(0 + " ");
}
else {
int result = TD[a][b];
System.out.print(result + " ");
}
}
System.out.println();
}
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
//before
TD = new int[n][n];
...
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
if (a == b) TD[a][b] = 0;
}
}
for (int k = 1; k <= n; k++) {
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
TD[a][b] = Math.min(TD[a][b], TD[a][k] + TD[k][b]);
}
}
}
//after
TD = new int[101][101];
...
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
if (a == b) TD[a][b] = 0;
}
}
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
if (c < TD[a][b]) TD[a][b] = c;
}
μ€μ νμ΄ μκ° : 40λΆ(첫 νμ΄ μκ° ν¬ν¨)
import java.util.*;
public class Main {
static final int INF = (int) 1e9;
static int n;
static int m;
public static int[][] TD;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
TD = new int[101][101];
for (int i = 0; i < 101; i++) {
Arrays.fill(TD[i], INF);
}
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
if (a == b) TD[a][b] = 0;
}
}
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
if (c < TD[a][b]) TD[a][b] = c;
}
for (int k = 1; k <= n; k++) {
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
TD[a][b] = Math.min(TD[a][b], TD[a][k] + TD[k][b]);
}
}
}
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= n; b++) {
if (TD[a][b] == INF) {
System.out.print(0 + " ");
}
else {
int result = TD[a][b];
System.out.print(result + " ");
}
}
System.out.println();
}
}
}