SMALL

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

 

1697번: 숨바꼭질

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일

www.acmicpc.net

 


  • 문제


  • 문제풀이

move는 a+1, a-1, a*2 3개로 나누어 BFS를 확인한다.


  • 코드 1
using System;
using System.Collections.Generic;

namespace ConsoleApp2
{
    internal class Program
    {
        public static int[] graph = new int[100001];
        public static bool[] visit = new bool[100001];
        public static int[] move = new int[3];
        public static int num;

        static void Main(string[] args)
        {
            int[] input = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
            int N = input[0];
            int K = input[1];

            bfs(N, K);

            Console.WriteLine(num);
        }

        public static void bfs(int startX, int targetX)
        {
            Queue<int> queue = new Queue<int>();
            queue.Enqueue(startX);
            visit[startX] = true;

            while (queue.Count > 0)
            {
                int a = queue.Dequeue();

                move[0] = a - 1;
                move[1] = a + 1;
                move[2] = a * 2;

                for (int k = 0; k < move.Length; k++)
                {
                    int x = move[k];

                    if (x >= 0 && x <= 100000 && !visit[x])
                    {
                        graph[x] = graph[a] + 1;
                        queue.Enqueue(x);
                        visit[x] = true;

                        if (x == targetX)
                        {
                            num = graph[x];
                            return;
                        }
                    }
                }
            }
        }
    }
}

 


  • 후기

예전에 좀비에 전염된다는 문제를 풀었던 코드가 있어 일부 수정했다.

LIST

+ Recent posts