티스토리 뷰
플로이드 알고리즘은 그래프의 모든 꼭지점 사이의 최단거리를 구하는 알고리즘이다.
- 음수 가중치를 갖는 간선도 순환만 없다면 처리할 수 있다.
- 3개의 for문을 이용하여 처리한다.
- 바깥 for 문은 중간지점, 가운데 for 문은 시작지점, 안쪽 for 문은 종료지점이다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
/** | |
* 백준, 11404 | |
* 플로이드 | |
* | |
* @author whitebeard-k | |
* | |
*/ | |
public class Problem11404 { | |
static int N; | |
static int M; | |
static int[][] maps; | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
N = sc.nextInt(); | |
M = sc.nextInt(); | |
maps = new int[N+1][N+1]; | |
for(int i = 0; i < M; i++) { | |
int from = sc.nextInt(); | |
int to = sc.nextInt(); | |
int cost = sc.nextInt(); | |
// 거리중 최소값으로 입력 | |
if(maps[from][to] == 0) { | |
maps[from][to] = cost; | |
} else { | |
maps[from][to] = Math.min(cost, maps[from][to]); | |
} | |
} | |
sc.close(); | |
for(int mid = 1; mid <= N; mid++){ | |
for(int start = 1; start <= N; start++){ | |
if(maps[start][mid] == 0) // 연결이 안되면 처리 안함 | |
continue; | |
for(int end = 1; end <= N; end++){ | |
if(maps[mid][end] == 0 || start == end) | |
continue; | |
// 중간 경로를 거쳐 가는 것이 그냥 가는것보다 빠르면 수정 | |
if(maps[start][end] == 0 || maps[start][end] > maps[start][mid] + maps[mid][end]) { | |
maps[start][end] = maps[start][mid] + maps[mid][end]; | |
} | |
} | |
} | |
} | |
for(int x = 1; x <= N; x++){ | |
for(int y = 1; y <= N; y++) { | |
System.out.printf("%d ", maps[x][y]); | |
} | |
System.out.println(); | |
} | |
} | |
} |
백준 11404 플로이드 - https://www.acmicpc.net/problem/11404
반응형
'알고리즘' 카테고리의 다른 글
[스크랩] 삼성 SW 검정에 도움이 되는 사이트 모음 (0) | 2018.01.09 |
---|---|
[알고리즘] 큐를 이용하여 스택처럼 사용하기 (0) | 2017.12.01 |
[알고리즘] 최소비용 신장트리 - 프림알고리즘 (0) | 2017.04.18 |
[알고리즘] 조합 (0) | 2017.04.17 |
[알고리즘] 알고리즘 강좌 자료와 온라인 문제 사이트 (0) | 2017.01.17 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- bash
- build
- Linux
- 백준
- mysql
- oozie
- error
- 오류
- yarn
- SQL
- S3
- 정올
- ubuntu
- nodejs
- Tez
- hbase
- HIVE
- emr
- HDFS
- 하이브
- Hadoop
- AWS
- java
- 하둡
- 다이나믹
- SPARK
- 파이썬
- 알고리즘
- Python
- airflow
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함