[백준] 1063 - 킹
1. 문제
2. 개요
8 * 8 체스판에 킹과 돌이 하나씩 있다.
킹은 상하좌우 + 대각선으로 총 8방향으로 한 칸씩 움직일 수 있다.
만약 킹이 이동할 위치에 돌이 있다면 돌을 킹이 움직이는 방향으로 움직인 후 킹을 이동시킨다.
만약 킹이나 돌이 체스판 외부로 이동하려 하면 해당 이동은 취소된다.
킹과 돌의 첫 위치와 N개의 킹의 이동 명령이 주어졌을 때, 킹과 돌의 최종 위치를 구하는 문제.
3. 풀이 및 코드
3-1. 풀이
가로열이 숫자가 아니라 ABC .. H 인 문자로 주어진다. 이를 숫자로 변환시켜 저장해둔다.
이동 명령 및 주어진 조건에 따라 킹과 돌을 이동시킨다.
모든 이동을 완료한 후, 다시 위치 좌표의 가로열을 문자로 변환시켜 출력한다.
3-2. Python
import sys
king, stone, N = sys.stdin.readline().split()
king = list(map(int, [ord(king[0]) - 64, king[1]]))
stone = list(map(int, [ord(stone[0]) - 64, stone[1]]))
N = int(N)
move = {'T' : [0, 1], 'LT' : [-1, 1], 'L' : [-1, 0], 'LB' : [-1, -1], 'B' : [0, -1], 'RB' : [1, -1], 'R' : [1, 0], 'RT' : [1, 1]}
for i in range(N):
command = sys.stdin.readline().rstrip()
dirX, dirY = move[command][0], move[command][1]
if king[0] + dirX < 1 or king[0] + dirX > 8 or king[1] + dirY < 1 or king[1] + dirY > 8:
continue
if king[0] + dirX == stone[0] and king[1] + dirY == stone[1]:
if stone[0] + dirX < 1 or stone[0] + dirX > 8 or stone[1] + dirY < 1 or stone[1] + dirY > 8:
continue
stone = [stone[0] + dirX, stone[1] + dirY]
king = [king[0] + dirX, king[1] + dirY]
print("%s%s" %(chr(king[0] + 64), king[1]))
print("%s%s" %(chr(stone[0] + 64), stone[1]))
3-3. C#
namespace boj_1063
{
internal class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
string[] input = sr.ReadLine().Split();
int[] king = { input[0][0] - 'A' + 1, input[0][1] - '0' };
int[] stone = { input[1][0] - 'A' + 1, input[1][1] - '0' };
int N = int.Parse(input[2]);
Dictionary<string, int[]> move = new Dictionary<string, int[]>()
{
{ "T" , new int[] { 0, 1 } }, { "LT", new int[] { -1, 1 } }, { "L", new int[] { -1, 0 } }, { "LB", new int[] { -1, -1 } },
{ "B" , new int[] { 0, -1 } }, { "RB", new int[] { 1, -1 } }, { "R", new int[] { 1, 0 } }, { "RT", new int[] { 1, 1 } }
};
for (int i = 0; i < N; i++)
{
string command = sr.ReadLine().TrimEnd();
int dirX = move[command][0];
int dirY = move[command][1];
if (king[0] + dirX < 1 || king[0] + dirX > 8 || king[1] + dirY < 1 || king[1] + dirY > 8)
continue;
if (king[0] + dirX == stone[0] && king[1] + dirY == stone[1])
{
if (stone[0] + dirX < 1 || stone[0] + dirX > 8 || stone[1] + dirY < 1 || stone[1] + dirY > 8)
continue;
stone[0] += dirX;
stone[1] += dirY;
}
king[0] += dirX;
king[1] += dirY;
}
sw.WriteLine($"{(char)(king[0] + 64)}{king[1]}");
sw.WriteLine($"{(char)(stone[0] + 64)}{stone[1]}");
sw.Close();
}
}
}
Comments