[Algorithm] 99클럽 코테 스터디 7일차 TIL | 백준_숨바꼭질(1697번)

2025. 1. 21. 13:40·Algorithm

https://www.acmicpc.net/problem/1697


가벼운 문제라고 생각했는데 생각보다 오래걸렸다ㅠㅠ

가장 빠른 시간을 찾는 문제이므로 dfs보다 bfs가 적합하다고 생각했다

 

Node를 queue에 넣어서 풀이했는데, Node 에는 현재 위치와 걸린 시간을 넣어준다.

class Node{
    int location;
    int time;

    public Node(int location, int time){
        this.location = location;
        this.time = time;
    }
}

 

현재 위치를 기준으로 움직인 값들을 다시 큐에 넣고

location+1

location-1

location*2 

int[] arr = new int[3];
arr[0] = l+1;
arr[1] = l-1;
arr[2] = l*2;

for (int a : arr) {
    if (a >= 0 && a <= 100000 && !visited[a]) {
        queue.add(new Node(a, t + 1));
    }
}

 

현재 위치가 동생 위치와 같다면 반복문을 빠져나온다.

if (l == target) {
    answer = t;
    break;
}

 

처음에 방문 검사를 하지않아 메모리 초과 오류가 났었고 

방문 검사 후 범위 검사를 하여 ArrayIndexOutOfBounds 에러가 났었다.

if( !visited[a] && a >= 0 && a <= 100000 )

 

최종 풀이

import java.util.*;
import java.io.*;
class Main{
    static int answer;
    static boolean[] visited;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N = Integer.parseInt(st.nextToken()); //수빈 위치
        int K = Integer.parseInt(st.nextToken()); //동생 위치
        visited = new boolean[100001];
        bfs(N, K); //현재위치, 목적지
        System.out.println(answer);
    }
    public static void bfs(int location, int target) {
        Queue<Node> queue = new LinkedList<>();
        queue.add(new Node(location, 0));
        while (!queue.isEmpty()) {
            Node x = queue.poll();
            int l = x.location;
            int t = x.time;

            visited[l] = true;
            if (l == target) {
                answer = t;
                break;
            }
            
            int[] arr = new int[3];
            arr[0] = l+1;
            arr[1] = l-1;
            arr[2] = l*2;

            for (int a : arr) {
                if (a >= 0 && a <= 100000 && !visited[a]) {
                    queue.add(new Node(a, t + 1));
                }
            }
        }
    }
}
class Node{
    int location;
    int time;

    public Node(int location, int time){
        this.location = location;
        this.time = time;
    }
}

 

Node대신 int[] 풀이

import java.util.*;
import java.io.*;
class Main{
    static int answer;
    static boolean[] visited;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N = Integer.parseInt(st.nextToken()); //수빈 위치
        int K = Integer.parseInt(st.nextToken()); //동생 위치
        visited = new boolean[100001];
        bfs(N, K); //현재위치, 목적지
        System.out.println(answer);
    }
    public static void bfs(int location, int target) {
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{location, 0});
        while (!queue.isEmpty()) {
            int[] x = queue.poll();
            int l = x[0];
            int t = x[1];

            visited[l] = true;
            if (l == target) {
                answer = t;
                break;
            }
            
            int[] arr = {l-1, l+1, l*2};

            for (int a : arr) {
                if (a >= 0 && a <= 100000 && !visited[a]) {
                    queue.add(new int[]{a, t + 1});
                }
            }
        }
    }
}

 

 

'Algorithm' 카테고리의 다른 글

[Algorithm] 99클럽 코테 스터디 9일차 TIL | 백준_이분 그래프(1707번)  (0) 2025.01.23
[Algorithm] 99클럽 코테 스터디 8일차 TIL | 백준_단지번호붙이기(2667번)  (1) 2025.01.22
[Algorithm] 99클럽 코테 스터디 6일차 TIL | 백준_DFS와 BFS(1260번)  (4) 2025.01.20
[Algorithm] 99클럽 코테 스터디 5일차 TIL | 백준_두 용액(2470번)  (0) 2025.01.17
[Algorithm] 99클럽 코테 스터디 4일차 TIL | 백준_기타 레슨(2343번)  (10) 2025.01.16
'Algorithm' 카테고리의 다른 글
  • [Algorithm] 99클럽 코테 스터디 9일차 TIL | 백준_이분 그래프(1707번)
  • [Algorithm] 99클럽 코테 스터디 8일차 TIL | 백준_단지번호붙이기(2667번)
  • [Algorithm] 99클럽 코테 스터디 6일차 TIL | 백준_DFS와 BFS(1260번)
  • [Algorithm] 99클럽 코테 스터디 5일차 TIL | 백준_두 용액(2470번)
dev_ajrqkq
dev_ajrqkq
알고리즘 천재가 될 거야
  • dev_ajrqkq
    기록이 자산이다
    dev_ajrqkq
  • 전체
    오늘
    어제
    • 분류 전체보기 (147)
      • Front-end (0)
      • Back-end (11)
        • Spring (1)
        • Java (8)
      • CS (9)
        • 데이터베이스 (5)
        • 네트워크 (4)
      • Algorithm (80)
      • 이것저것 (0)
      • 버그잡기 (1)
      • TIL (37)
      • 후기 (1)
      • 취준 (0)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      TypeScript
      코딩테스트준비
      개발자취업
      항해99
      99클럽
      티스토리챌린지
      오블완
      Til
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.2
    dev_ajrqkq
    [Algorithm] 99클럽 코테 스터디 7일차 TIL | 백준_숨바꼭질(1697번)
    상단으로

    티스토리툴바