-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloyd.java
More file actions
55 lines (49 loc) · 1.43 KB
/
Floyd.java
File metadata and controls
55 lines (49 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package algorithm;
import java.util.Scanner;
/**
* @author taeheekim
*/
// 양의 가중치 버전
public class Floyd {
static final int INF = 9999999;
static int N,distance[][];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
distance = new int[N][N];
for(int i=0; i<N; ++i) {
for(int j=0; j<N; ++j) {
distance[i][j] = sc.nextInt();
if(i != j && distance[i][j]==0) {//자기자신으로의 인접 정보가 아니고 인접해있지 않다면 INF로 채우기
distance[i][j]=INF;
}
}
}
System.out.println("===========입력==========");
print();
// 출발지-->경유지-->목적지로 3중 루프 돌리면 오답
// 경유지-->출발지-->목적지로 3중 루프 돌려야 정답
for(int k=0; k<N; ++k) {
for(int i=0; i<N; ++i) {
if(i==k) continue; // 출발지와 경유지가 같다면 다음 출발지
for(int j=0; j<N; ++j) {
if(i==j || k==j) continue; // 경유지와 목적지가 같거나 출발지가 곧 목적지라면 패스
if(distance[i][j] > distance[i][k]+distance[k][j]) {
distance[i][j] = distance[i][k]+distance[k][j];
}
}
}
print();
}
sc.close();
}
private static void print() {
for(int i=0; i<N; ++i) {
for(int j=0; j<N; ++j) {
System.out.print(distance[i][j]+"\t");
}
System.out.println();
}
System.out.println("=====================================");
}
}