Programming/BOJ

[구현] 2174번 로봇 시뮬레이션

거북이주인장 2022. 3. 17. 21:15

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

알고리즘

  • 구현, 시뮬레이션

풀이

포인트

  • 파이썬 class를 이용해서 구현하기

구현, 시뮬레이션

  1. 로봇의 위치, 방향, 번호의 정보를 가지는 robot class를 만든다.
  2. $B \times A$ 크기의 land 2차원 배열을 선언하고, $(x,y)$ 좌표에 로봇이 있을 경우, 해당 위치에 로봇 클래스를 추가한다.
  3. 로봇의 개수만큼의 크기를 가지는 robot_info 1차원 배열을 선언하고 i번째 위치에 i번 로봇 클래스를 추가한다.
  4. 문제의 명령을 그대로 수행한다. 벽에 만나거나, 다른 로봇을 만나면 경고문과 함께 프로그램을 종료하고 그렇지 않다면 land 배열에서 로봇을 옮기거나 로봇 클래스의 방향을 수정해준다.

[Source Code]

a,b = map(int,input().split())
n,m = map(int,input().split())
class robot:
    def __init__(self,x,y,d,num):
        self.x = x
        self.y = y
        self.d = d
        self.num = num
robot_info = []
land = [[[] for _ in range(a)] for _ in range(b)]
dx = [-1,0,1,0]
dy = [0,1,0,-1]
dct = {'N':0,'E':1,'S':2,'W':3}
for i in range(n):
    y,x,d = input().split()
    x = int(x)
    y = int(y)
    x = b-x
    y -= 1
    d = dct[d]
    r = robot(x,y,d,i)
    robot_info.append(r)
    land[x][y].append(r)
for _ in range(m):
    number,order,cnt = input().split()
    number = int(number)-1
    cnt = int(cnt)
    for _ in range(cnt):
        r = robot_info[number]
        x,y,d = r.x,r.y,r.d
        if order == 'L':
            r.d = (d-1)%4
        elif order == 'R':
            r.d = (d+1)%4
        elif order == 'F':
            nx,ny = x+dx[d],y+dy[d]
            if not (0 <= nx < b and 0 <= ny < a):
                print(f'Robot {number+1} crashes into the wall')
                exit()
            if len(land[nx][ny]) >= 1:
                another_r = land[nx][ny][0]
                print(f'Robot {number + 1} crashes into robot {another_r.num + 1}')
                exit()
            r.x = nx
            r.y = ny
            land[nx][ny].append(r)
            land[x][y].clear()
print('OK')