순서대로 전체층, 시작층, 목표층, 올라갈층, 내려갈층 를 입력받고
큐에 시작층과, 버튼을 누르지 않았으므로 0을 add후 while문을 돌려준다
방문하지 않은 층만 방문할수 있고,
(층+올라갈층) 은 전체층을 넘기면 안되고 ,
(층-내려갈층) 은 1층 이상이어야 한다.
현재층이 목표층에 도달했으면 클릭 수를 리스트에 저장한다.
while문이 끝나면 리스트에서 제일 작은 수를 꺼내서 출력
해당 층에 방문여부를 (층+올라갈층) 보다 늦게 검증해서 조금 틀렸다...
package com.exam.BFSDFS;
import java.util.*;
public class B5014 {
static int F,S,G,U,D;
static ArrayList<Integer> res = new ArrayList<>();
static boolean[] visited;
static class Node{
int n,c;
Node(int now, int click){
n=now;
c=click;
}
}
static void bfs(){
Queue<Node> queue = new LinkedList<>();
visited[S] = true;
queue.add(new Node(S,0));
while(!queue.isEmpty()){
Node temp = queue.remove();
if(temp.n==G){
res.add(temp.c);
break;
}
if((temp.n-D)>0 && !visited[temp.n-D]){
int down = temp.n-D;
visited[down] = true;
queue.add(new Node(down,temp.c+1));
}
if((temp.n+U)<=F && !visited[temp.n+U]){
int up = temp.n +U;
visited[up] = true;
queue.add(new Node(up,temp.c+1));
}
}
if(!visited[G]) {
System.out.println("use the stairs");
}
else{
Collections.sort(res);
System.out.println(res.get(0));
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
F = sc.nextInt();
S = sc.nextInt(); //시작위치
G = sc.nextInt();
U = sc.nextInt();
D = sc.nextInt();
visited = new boolean[F+1];
bfs();
}
}
'연습문제 > JAVA' 카테고리의 다른 글
1697-숨바꼭질 (0) | 2022.08.11 |
---|---|
2573-빙산 (0) | 2022.08.10 |
14503-로봇청소기 (0) | 2022.08.10 |
7569-토마토 (0) | 2022.08.09 |
11724-연결 요소의 개수 (0) | 2022.08.09 |