SMALL
https://www.acmicpc.net/problem/7562
7562번: 나이트의 이동
체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수
www.acmicpc.net
- 문제
- 문제풀이
BFS를 사용하여 만든다. dx와 dy를 나이트가 움직이는 좌표로 설정해주어야한다.
- 코드 1
using System;
using System.Collections.Generic;
namespace YONGYONG2
{
class Program
{
public static int[] dx = { -2, -1, 1, 2, 2, 1, -1, -2 };
public static int[] dy = { 1, 2, 2, 1, -1, -2, -2, -1 };
public static int[,] chessBoard;
public static int size;
static void Main(string[] args)
{
int T = int.Parse(Console.ReadLine());
for (int t = 0; t < T; t++)
{
size = int.Parse(Console.ReadLine());
chessBoard = new int[size, size];
int[] start = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
int[] target = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
int result = bfs(start[0], start[1], target[0], target[1]);
Console.WriteLine(result);
}
}
public static int bfs(int startX, int startY, int targetX, int targetY)
{
Queue<(int, int)> queue = new Queue<(int, int)>();
queue.Enqueue((startX, startY));
chessBoard[startX, startY] = 1;
while (queue.Count > 0)
{
(int x, int y) = queue.Dequeue();
if (x == targetX && y == targetY)
return chessBoard[x, y] - 1;
for (int k = 0; k < 8; k++)
{
int nx = x + dx[k];
int ny = y + dy[k];
if (nx >= 0 && nx < size && ny >= 0 && ny < size && chessBoard[nx, ny] == 0)
{
queue.Enqueue((nx, ny));
chessBoard[nx, ny] = chessBoard[x, y] + 1;
}
}
}
return -1;
}
}
}
- 후기
공학수학으로 선형방정식의 행렬계산법을 배웠는데 이게 이렇게 쓰일 줄 몰랐다.
LIST
'백준 > C#' 카테고리의 다른 글
[C#]백준 1697번: 숨바꼭질 (0) | 2023.07.24 |
---|---|
[C#]백준 7576번: 토마토 (0) | 2023.07.24 |
[C#]TopCoder 알고리즘 트레이닝 : 미로 만드는 사람 (0) | 2023.07.24 |
[C#]백준 19532번: 수학은 비대면강의입니다 (0) | 2023.07.20 |
[C#]백준 2217번: 로프 (0) | 2023.07.20 |