๐ŸŽฏ Coding Test

[๋ฐฑ์ค€] 1697 ์ˆจ๋ฐ”๊ผญ์งˆ 1์ฐจ์› BFS

์—ฐ_์šฐ๋ฆฌ 2022. 2. 12. 19:22
๋ฐ˜์‘ํ˜•

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

 

1697๋ฒˆ: ์ˆจ๋ฐ”๊ผญ์งˆ

์ˆ˜๋นˆ์ด๋Š” ๋™์ƒ๊ณผ ์ˆจ๋ฐ”๊ผญ์งˆ์„ ํ•˜๊ณ  ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ํ˜„์žฌ ์  N(0 ≤ N ≤ 100,000)์— ์žˆ๊ณ , ๋™์ƒ์€ ์  K(0 ≤ K ≤ 100,000)์— ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ๊ฑท๊ฑฐ๋‚˜ ์ˆœ๊ฐ„์ด๋™์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋งŒ์•ฝ, ์ˆ˜๋นˆ์ด์˜ ์œ„์น˜๊ฐ€ X์ผ

www.acmicpc.net

 

 

๋ฌธ์ œํ’€์ด

1์ฐจ์› BFS์ด๋‹ค.

2์ฐจ์› BFS์˜ check ๋ณ€์ˆ˜๋ฅผ node๋กœ ์‚ฌ์šฉํ•œ๋‹ค.

 

 

์ œ์ถœ์ฝ”๋“œ

package baekjoon;

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

public class Main1697 {

    static int length = 100000;
    static int[] node = new int[length+1];
    static Queue<Integer> queue = new LinkedList<>();
    static int goal;

    public static void main(String[] args) throws IOException {
        Scanner scan = new Scanner(System.in);
        int start = scan.nextInt();
        goal = scan.nextInt();

        int time = bfs(start)-1;
        System.out.println(time);
    }

    private static int bfs(int start) {
        queue.offer(start);
        node[start] = 1;   //0์ดˆ๋กœ ํ•˜๋ฉด ๋ฐฉ๋ฌธํ–ˆ๋Š”์ง€ ์•Œ ์ˆ˜ ์—†๊ธฐ๋•Œ๋ฌธ์— 1์ดˆ๋กœ ๊ธฐ์žฌํ•˜๊ณ , ๊ฒฐ๊ณผ๊ฐ’์—์„œ -1 ํ•˜๊ธฐ๋กœํ•œ๋‹ค

        while(!queue.isEmpty()){
            int temp = queue.poll();
            //System.out.print("time : " + node[temp] + ", ํ˜„์žฌ๋…ธ๋“œ : " + temp + ", ๋ฐฉ๋ฌธ๋…ธ๋“œ : ");

            //์›€์ง์ผ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์˜ ๊ฐ€์ง€ ์ˆ˜
            int index = 0;
            for (int i = 0; i < 3; i++) {
                switch (i){
                    case 0 : index = temp-1; break;
                    case 1 : index = temp+1; break;
                    case 2 : index = temp*2; break;
                }

                if(index >=0 && index <= length && node[index] == 0){  //๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๊ณณ์ด๋ผ๋ฉด
                    //node[index] == 0 ๋งŒ ํ–ˆ๋”๋‹ˆ ArrayIndexOutOfBounds๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.
                    // index >=0 && index <= length ๋ฅผ ๋’ค์— ๋ถ™์—ฌ์ฃผ์–ด๋„ ๋™์ผํ•˜๊ฒŒ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.
                    queue.offer(index);
                    node[index] = node[temp] + 1;
                }
                //System.out.print(index + ", ");

                if(index == goal){
                    return node[index];
                }
            }
            //System.out.println();
        }
        return 0;
    }

}
๋ฐ˜์‘ํ˜•
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ํŠธ์œ„ํ„ฐ ๊ณต์œ ํ•˜๊ธฐ
  • ๊ตฌ๊ธ€ ํ”Œ๋Ÿฌ์Šค ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜คํ†ก ๊ณต์œ ํ•˜๊ธฐ