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

 

7562번: 나이트의 이동

체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수

www.acmicpc.net

 

문제 풀이

토마토 문제와 비슷하게 이동할 수 있는 좌표를 저장해 놓고 2차원 배열 탐색

  • 나이트 이동 반경을 배열로 저장
  • BFS로 나이트의 이동을 탐색, 이전 값에 +1을 해서 점점 늘리기
  • 시작이 1이었으니 출력할 때는 -1 해줘서 출력
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Baekjoon.silver
{
    class _7562
    {
        static void Main(string[] args)
        {
            StringBuilder stb = new StringBuilder();
            (int, int)[] move = { (-2, -1), (-2, 1), (-1, -2), (-1, 2), (2, -1), (2, 1), (1, -2), (1, 2) };

            int t = int.Parse(Console.ReadLine());
            for(int test = 0; test<t; test++)
            {
                int size = int.Parse(Console.ReadLine());
                int[,] chess = new int[size, size];

                int[] n = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
                chess[n[0], n[1]] = 1;

                int[] destination = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);

                Queue<(int, int)> que = new Queue<(int, int)>();
                que.Enqueue((n[0], n[1]));
                while(que.Count > 0)
                {
                    (int, int) temp = que.Dequeue();
                    for(int i = 0; i<8; i++)
                    {
                        int x = temp.Item1 + move[i].Item1;
                        int y = temp.Item2 + move[i].Item2;

                        if ((x >= 0 && x<size) && (y>= 0 && y < size))
                        {
                            if (chess[x,y] == 0)
                            {
                                que.Enqueue((x,y));
                                chess[x, y] = chess[temp.Item1, temp.Item2] + 1;
                            }
                        }
                    }

                    if (chess[destination[0], destination[1]] != 0)
                        break;
                }

                stb.AppendLine((chess[destination[0], destination[1]]-1).ToString());
            }

            Console.WriteLine(stb);
        }
    }
}

'문제 풀이 > C#' 카테고리의 다른 글

[9251] - LCS  (0) 2022.11.02
[1918] - 후위 표기식  (0) 2022.11.01
[2565] - 전깃줄  (0) 2022.10.30
[11054] - 가장 긴 바이토닉 부분 수열  (0) 2022.10.29
[1992] - 쿼드트리  (0) 2022.10.18

+ Recent posts