티스토리 뷰
728x90



문제 풀이 과정
플로이드-워셜 알고리즘을 학습 할 수 있는 기본적인 문제라고 생각한다. 플로이드-워셜 알고리즘을 그대로 사용하여 문제를 해결하였다.
다만 제출 할때 항상 98% 에서 틀렸습니다가 나와서 의문이였다.
알고보니 MAX 값으로 잡았던 값이 작아서 문제가 되었다. 여기서 MAX 값을 Integer.MAX_VALUE 로 잡으면 오버플로워가 발생하게 된다.
전체 코드
This file contains hidden or 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.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.util.StringTokenizer; | |
public class Main { | |
static int[][] distance; | |
static int city, bus; | |
static final int MAX = 10000001; | |
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
public static void main(String[] args) throws IOException { | |
city = Integer.parseInt(br.readLine()); | |
bus = Integer.parseInt(br.readLine()); | |
distance = new int[city + 1][city + 1]; | |
for (int i = 1; i <= city; i++) { | |
for (int j = 1; j <= city; j++) { | |
if(i == j){ | |
distance[i][j] = 0; | |
} | |
else{ | |
distance[i][j] = MAX; | |
} | |
} | |
} | |
input(); | |
floyd(); | |
print(); | |
} | |
public static void input() throws IOException { | |
for (int i = 0; i < bus; i++) { | |
StringTokenizer st = new StringTokenizer(br.readLine()); | |
int a = Integer.parseInt(st.nextToken()); | |
int b = Integer.parseInt(st.nextToken()); | |
int c = Integer.parseInt(st.nextToken()); | |
if(distance[a][b] > c) distance[a][b] = c; | |
} | |
} | |
public static void floyd(){ | |
for (int k = 1; k <= city; k++) { | |
for (int i = 1; i <= city; i++) { | |
for (int j = 1; j <= city; j++) { | |
if(distance[i][j] > distance[i][k] + distance[k][j]){ | |
distance[i][j] = distance[i][k] + distance[k][j]; | |
} | |
} | |
} | |
} | |
} | |
public static void print(){ | |
for (int i = 1; i <= city; i++) { | |
for (int j = 1; j <= city; j++) { | |
if(distance[i][j] == MAX){ | |
System.out.print(0 + " "); | |
} | |
else{ | |
System.out.print(distance[i][j] + " "); | |
} | |
} | |
System.out.println(); | |
} | |
} | |
} |

728x90
'Algorithm > Baekjoon' 카테고리의 다른 글
백준 9663번 - N-Queen (JAVA) (0) | 2023.01.21 |
---|---|
백준 1202번 - 보석 도둑 (0) | 2023.01.20 |
백준 16120번 - PPAP (JAVA) (0) | 2023.01.18 |
백준 1915번 - 가장 큰 정사각형 (JAVA) (0) | 2023.01.17 |
백준 1484번 - 다이어트 (JAVA) (0) | 2023.01.17 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 개발자 취준
- 제로베이스 백엔드 스쿨
- 백준
- 자바
- 기술 면접 준비
- 취업 준비
- 알고리즘
- 코딩테스트
- 알고리즘 공부
- 코테공부
- 백엔드 개발자 기술 면접 준비
- 백엔드 개발자 취업 준비
- 코딩테스트 준비
- 자바공부
- 취준
- 코딩테스트공부
- 프로그래머스 카카오
- java
- 개발자 면접 준비
- 취업준비
- 알고리즘공부
- 프로그래머스
- 개발자 취업 준비
- 제로베이스 백준 장학금
- 백엔드 개발자
- 코테 준비
- 코테준비
- 프로그래머스 자바
- 코딩테스트 공부
- 주니어 개발자 취업 준비
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함