[BOJ][C#] 3190 뱀

LimJaeJun·2024년 2월 20일
0

PS/BOJ

목록 보기
106/108

📕 문제

📌 링크

📗 접근 방식

  • 뱀의 이동을 구현
    • 뱀은 머리 부분을 기준으로 상하좌우로 이동할 수 있습니다.
    • 뱀의 이동 방향은 시계방향 또는 반시계방향으로 회전할 수 있습니다.
    • 뱀은 사과를 먹으면 길이가 늘어나고, 사과가 없으면 꼬리 부분이 줄어듭니다.
    • 이동할 때마다 게임이 종료되는 조건을 확인합니다.
  • 게임이 종료되는 조건 체크
    • 뱀이 벽에 부딪히거나 자신의 몸과 부딪히는 경우 게임이 종료됩니다.
    • 게임이 종료되는 순간까지 걸린 시간을 반환합니다.

📘 코드

namespace BOJ
{
    class No_3190
    {
        static int N, K, L;
        static int[,] board;
        static Dictionary<int, char> dict = new Dictionary<int, char>();
        static LinkedList<(int, int)> snakes = new LinkedList<(int, int)>();
        static int[] dx = { 0, 1, 0, -1 };
        static int[] dy = { 1, 0, -1, 0 };

        static void Main()
        {
            N = int.Parse(Console.ReadLine());

            board = new int[N, N];

            K = int.Parse(Console.ReadLine());
            for (int i = 0; i < K; i++)
            {
                int[] inputs = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
                int x = inputs[0] - 1;
                int y = inputs[1] - 1;

                board[x, y] = 1;
            }

            L = int.Parse(Console.ReadLine());
            for (int i = 0; i < L; i++)
            {
                string[] inputs = Console.ReadLine().Split();
                int location = int.Parse(inputs[0]);
                char direction = char.Parse(inputs[1]);

                dict.TryAdd(location, direction);
            }

            snakes.AddLast((0, 0));
            int cx = 0, cy = 0;
            int d = 0;
            int timer = 0;
            while (true)
            {
                timer++;

                int nx = cx + dx[d];
                int ny = cy + dy[d];

                if (IsEnd(nx, ny)) break;

                if (board[nx, ny] == 1)
                {
                    board[nx, ny] = 0;
                    snakes.AddLast((nx, ny));
                }
                else
                {
                    snakes.AddLast((nx, ny));
                    snakes.RemoveFirst();
                }

                if (dict.ContainsKey(timer))
                {
                    if (dict[timer] == 'D')
                    {
                        d = (d + 1) % 4;
                    }
                    else
                    {
                        d = (d + 3) % 4;
                    }
                }

                cx = nx;
                cy = ny;
            }

            Console.WriteLine(timer);
        }

        static bool IsEnd(int nx, int ny)
        {
            if (nx < 0 || ny < 0 || nx >= N || ny >= N)
            {
                return true;
            }

            return snakes.Contains((nx, ny));
        }
    }
}

📙 오답노트

처음에 틀린 이유는 범위 체크를 잘 못했다.
무난한 시뮬레이션 문제였던 것 같다.

📒 알고리즘 분류

  • 구현
  • 자료 구조
  • 시뮬레이션
profile
Dreams Come True

0개의 댓글

관련 채용 정보