Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- toUpperCase()
- 배열
- 요세푸스 문제
- IS NOT NULL
- 빅오 표기법
- 너비 우선 탐색
- 분할 정복
- 정렬
- ListIterator
- 공간 복잡도
- BFS
- 백트래킹
- 그래프 탐색
- 연결 리스트
- 자료 구조
- 시간 복잡도
- 소수 판정
- 스택
- 문자열
- 큐
- 구현
- ifnull
- MySQL
- 거듭제곱
- 그리디 알고리즘
- 그래프 이론
- toLowerCase()
- 브루트포스
- 수학
- 정수론
Archives
- Today
- Total
배푸니까
[백준 / JAVA] 5014. 스타트링크 본문
반응형
https://www.acmicpc.net/problem/5014
5014번: 스타트링크
첫째 줄에 F, S, G, U, D가 주어진다. (1 ≤ S, G ≤ F ≤ 1000000, 0 ≤ U, D ≤ 1000000) 건물은 1층부터 시작하고, 가장 높은 층은 F층이다.
www.acmicpc.net
💻 풀이 결과
💯 최종 코드
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
// 리팩토링한 코드 !!
class Node {
int floor, cnt;
Node(int floor, int cnt) {
this.floor = floor;
this.cnt = cnt;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int F = sc.nextInt(); // 건물 총 층 수
int S = sc.nextInt(); // 강호 현재 위치
int G = sc.nextInt(); // 스타트링크 위치
int U = sc.nextInt(); // 위로 U층 가는 버튼
int D = sc.nextInt(); // 아래로 D층 가는 버튼
Queue<Node> queue = new LinkedList<>();
boolean[] visited = new boolean[F + 1];
boolean flag = false;
// cnt : 다음 층으로 가기 위해 눌러야 하는 버튼의 수라는 점에 유의 !!
queue.add(new Node(S, 0));
visited[S] = true;
while (!queue.isEmpty()) {
Node curr = queue.poll();
// 탈출 조건
if (curr.floor == G) {
System.out.println(curr.cnt);
flag = true;
queue.clear();
break;
}
int up = curr.floor + U;
int down = curr.floor - D;
if (up <= F && !visited[up]) {
queue.add(new Node(up, curr.cnt + 1));
visited[up] = true;
}
if (down > 0 && !visited[down]) {
queue.add(new Node(down, curr.cnt + 1));
visited[down] = true;
}
} // while문 끝
if (!flag) {
System.out.println("use the stairs");
}
}
}
💬 풀이 과정
- 건물의 총 층 수인 범위 내에서 U버튼과 D버튼을 각각 눌렀을 때를 BFS 돌린다.
- 눌러야 하는 버튼의 수의 최솟값을 구하기 위해 visited 방문 처리를 해준다.
💡 깨달은 점
1. 노드의 카운팅 요소
- BFS를 돌릴 때 노드에 저장하는 cnt 요소의 시작점이나 카운팅 지점에 유의해야 한다.
반응형
'백준' 카테고리의 다른 글
[백준 / JAVA] 10026. 적록색약 (0) | 2023.08.18 |
---|---|
[백준 / JAVA] 2468. 안전 영역 (0) | 2023.08.17 |
[백준 / JAVA] 2667. 단지번호붙이기 (0) | 2023.08.15 |
[백준 / JAVA] 2960. 에라토스테네스의 체 (0) | 2023.08.09 |
[백준 / JAVA] 7562. 나이트의 이동 (0) | 2023.08.06 |