본문 바로가기
알고리즘/너비 우선 탐색(bfs)

백준 5014번 : 스타트링크 java

by LDY3838 2022. 8. 5.
반응형

이 문제는 너비 우선 탐색을 이용하여 S층에서 G층으로 가기까지 눌러야 하는 버튼의 수의 최솟값을 구하는 문제입니다.

이 문제를 풀기 위해서는 U와 -D 만큼 현재 위치한 층에서 이동하면서 이미 방문한 층이라면 방문하지 않고 방문하지 않았다면 그 층으로 가기 위해서 필요한 버튼의 클릭수를 저장하면서 이동하면 됩니다.


import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        //F 총 층수, S 현재 위치, G 목표 위치
        int F = Integer.parseInt(st.nextToken());
        int S = Integer.parseInt(st.nextToken());
        int G = Integer.parseInt(st.nextToken());
        int U = Integer.parseInt(st.nextToken());
        int D = Integer.parseInt(st.nextToken());

        int[] dir = new int[2];
        dir[0] = U;
        dir[1] = -D;

        boolean[] visited = new boolean[F+1];
        int cnt = 0;
        boolean canGo = false;

        Queue<Node> q = new LinkedList<>();
        q.offer(new Node(S, 0));
        visited[S] = true;

        while(!q.isEmpty()){
            Node nowFloor = q.poll();

            if(nowFloor.vertex == G){
                canGo = true;
                cnt = nowFloor.cnt;
                break;
            }

            for(int i = 0; i<2; i++){
                int nextFloor = nowFloor.vertex + dir[i];

                if(nextFloor<1 ||nextFloor>F)
                    continue;
                if(visited[nextFloor])
                    continue;

                q.offer(new Node(nextFloor, nowFloor.cnt+1));
                visited[nextFloor] = true;
            }
        }

        if(canGo)
            System.out.println(cnt);
        else
            System.out.println("use the stairs");
    }
}
class Node{
    int vertex, cnt;

    Node(int vertex, int cnt){
        this.vertex = vertex;
        this.cnt = cnt;
    }
}
반응형

댓글