[백준 5014] 스타트링크

like0·2022년 8월 19일
0

코테준비(JAVA)

목록 보기
20/37

생각정리

F : 사무실의 층수
G : 목적지의 위치(층수)
S : 강호가 현재 있는 곳
U, D : 엘레베이터에 존재하는 버튼 (각각 위로 U층, 아래로 D층 이동)

현재 층에서 할 수 있는 것 : 위로 U층 또는 아래로 D층
이동한 층이 1층보다 아래거나, 사무실의 층수를 벗어나면 continue;
그렇지 않으면 탐색하는 층을 queue에 넣기
그러다 num[nx][ny] 가 G와 같으면 그때의 버튼 수 출력

1 -> 3 -> 5 -> 7 -> 9 -> 11 -> 13 ...
							-> 10 ...
					-> 8 -> 10
                    	-> 7
				-> 6 -> 8
                	-> 5
			-> 4 -> 6
            	-> 3
		-> 2 -> 4
        	-> 1
            
  -> 0 5 7 9 11 10

생각하지 못한 것

  1. 현재 있는 곳과 목적지의 위치(층수)가 같을 때, use the stairs이 아닌 0이 출력되어야 한다.
  2. 층수의 시작은 0이 아닌 1이다.

코드

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

public class Main {
    static int  F, S, G, U, D;
    static boolean[] visited;
    static int[] dist;
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        F = Integer.parseInt(st.nextToken()); //전체 층수
        S = Integer.parseInt(st.nextToken()); //현재위치
        G = Integer.parseInt(st.nextToken()); //목적지 층수
        U = Integer.parseInt(st.nextToken()); //위로 갈 수 있는 층수
        D = Integer.parseInt(st.nextToken()); //아래로 갈 수 있는 층수
        visited = new boolean[F+1];
        dist = new int[F+1];
        if(S == G){
            System.out.println(0);
            return ;
        }
        bfs(S);

    }

    static void bfs(int x) {
        Queue<Integer> queue = new LinkedList<>();
        int[] move = {U, -D};
        queue.add(x);
        visited[x] = true;
    
        while(!queue.isEmpty()) {
            int out = queue.poll();

            for(int i=0; i<2; i++) {
                int next = out + move[i];

                if(next < 1 || next > F) continue;
                else if(visited[next]) continue;
                else {
                    queue.add(next);
                    visited[next] = true;
                    dist[next] = dist[out] + 1;
                    //System.out.println("dist[next] " + dist[next]);
                    if(next == G){
                        System.out.println(dist[next]);
                        return ;
                    }
                }

            }
        }

        System.out.println("use the stairs");
        return ;
    }
    
}
profile
배우고 성장하는 개발자가 되기!

0개의 댓글