Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

21.07.07 - [BOJ] 1697. 숨바꼭질 #119

Closed
suhyunsim opened this issue Jul 8, 2021 · 0 comments
Closed

21.07.07 - [BOJ] 1697. 숨바꼭질 #119

suhyunsim opened this issue Jul 8, 2021 · 0 comments
Assignees
Labels
BFS 너비 우선 탐색 실버 BOJ - 실버 실패 시도했지만 맞지 못한 문제

Comments

@suhyunsim
Copy link
Owner

suhyunsim commented Jul 8, 2021

문제

핵심 아이디어

  • BFS로 풀이
  • 큐에 수빈이의 위치를 넣어가면서 이동시킨다
  • 한 번 방문한 곳은 다시 방문하지 않는 것이 좋기 때문에, 따로 배열에 체크하면서 방문
  • check[i] = i를 방문했는지
  • dist[i] = i를 몇 번만에 방문했는지

어려운 점, 실수

풀이

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

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

        int n = Integer.parseInt(st.nextToken());
        int k = Integer.parseInt(st.nextToken());
        int MAX = 200000;
        Queue<Integer> queue = new LinkedList<>();
        int[] dist = new int[MAX];
        boolean[] check = new boolean[MAX];
        check[n] = true;
        dist[n] = 0;
        
        queue.offer(n);
        while (!queue.isEmpty()) {
            int now = queue.poll();
            if (now - 1 >= 0) {
                if(!check[now - 1]) {
                    queue.offer(now - 1);
                    check[now - 1] = true;
                    dist[now - 1] = dist[now] + 1;
                }
            }
            if (now + 1 < MAX) {                
                if (!check[now + 1]) {
                    queue.offer(now + 1);
                    check[now + 1] = true;
                    dist[now + 1] = dist[now] + 1;
                }
            }
            if (now * 2 < MAX) {
                if (!check[now * 2]) {
                    queue.offer(now * 2);
                    check[now * 2] = true;
                    dist[now * 2] = dist[now] + 1;                    
                }
            }
        }
        bw.write(String.valueOf(dist[k]));
        bw.flush();
        bw.close();
        br.close();
    }    
}
@suhyunsim suhyunsim added 실패 시도했지만 맞지 못한 문제 스택 stack BFS 너비 우선 탐색 labels Jul 8, 2021
@suhyunsim suhyunsim added this to the 7월 2주 차 milestone Jul 8, 2021
@suhyunsim suhyunsim self-assigned this Jul 8, 2021
@suhyunsim suhyunsim added 실버 BOJ - 실버 and removed 스택 stack labels Jul 8, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
BFS 너비 우선 탐색 실버 BOJ - 실버 실패 시도했지만 맞지 못한 문제
Projects
None yet
Development

No branches or pull requests

1 participant