프로그래밍/알고리즘

BOJ 2174 · 로봇 시뮬레이션

반응형


알고리즘 분류 : 시뮬레이션  


로봇의 움직임을 그대로 구현하는 문제다. 문제의 조건을 그대로 구현하면 된다. 동서남북의 방향과 회전의 방향에만 유의하면 큰 어려움은 없다.


  • 아래 코드에서는 다음과 같이 구현하였다.
  • 로봇의 번호가 적혀있는 맵을 가로(A)*세로(B) 사이즈로 만들어둔다.
  • 로봇의 좌표 위치와 회전 방향이 적혀있는 배열을 로봇의 개수(N) 만큼 만들어둔다.
  • 남동북서 순서로 인덱스를 매긴다. S(0), E(1), N(2), W(3)
  • 왼쪽 회전 : S(0)→E(1), E(1)→N(2), N(2)→W(3), W(3)→S(0) 
  • 오른쪽 회전 : S(0)→W(3), E(1)→S(0), N(2)→E(1), W(3)→N(2)
  • 회전은 나머지 연산을 하면 된다. 왼쪽 회전 : (인덱스+1)%4, 오른쪽 회전 : (인덱스+3)%4
  • 이후 주어지는 M번의 명령을 수행한다.




C++ 소스코드


#include <cstdio>

struct robot {
    int x, y, z;
};

int A, B, N, M;
int w[101][101];
robot r[101];
const int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};

bool solve(int id, char direct, int cnt) {
    int &x = r[id].x, &y = r[id].y, &z = r[id].z;
    w[x][y] = 0;
    while (cnt--) {
        if (direct == 'L') z = (z+1)%4;
        else if (direct == 'R') z = (z+3)%4;
        else {
            x += dx[z], y += dy[z];
            if (x < 1 || x > B || y < 1 || y > A) {
                printf("Robot %d crashes into the wall\n", id);
                return true;
            }
            if (w[x][y]) {
                printf("Robot %d crashes into robot %d\n", id, w[x][y]);
                return true;
            }
        }
    }
    w[x][y] = id;
    return false;
}

int main() {
    scanf("%d %d", &A, &B);
    scanf("%d %d", &N, &M);
    for (int i=1; i<=N; i++) {
        int x, y;
        char z;
        scanf("%d %d %c", &x, &y, &z);
        w[y][x] = i;
        if (z == 'S') z = 0;
        else if (z == 'E') z = 1;
        else if (z == 'N') z = 2;
        else z = 3;
        r[i] = {y, x, z};
    }
    bool crash = false;
    while (M--) {
        int id, cnt;
        char direct;
        scanf("%d %c %d", &id, &direct, &cnt);
        if (!crash) crash = solve(id, direct, cnt);
    }
    if (!crash) printf("OK\n");
    return 0;
}




Python 3 소스코드


import sys
input = sys.stdin.readline

A, B = map(int, input().split())
N, M = map(int, input().split())
D = {'S': 0, 'E': 1, 'N': 2, 'W': 3}
dx, dy = (-1, 0, 1, 0), (0, 1, 0, -1)
w = [[0]*(A+1) for _ in range(B+1)]
r = [[0, 0, 0] for _ in range(N+1)]

def solve(i, d, c):
    x, y, z = r[i]
    w[x][y] = 0
    for _ in range(c):
        if d == 'L':
            z = (z+1)%4
        elif d == 'R':
            z = (z+3)%4
        else:
            x, y = x+dx[z], y+dy[z]
            if x < 1 or x > B or y < 1 or y > A:
                print("Robot %d crashes into the wall" % i)
                return True
            if w[x][y]:
                print("Robot %d crashes into robot %d" % (i, w[x][y]))
                return True
    r[i] = x, y, z
    w[x][y] = i
    return False

for i in range(1, N+1):
    x, y, z = input().split()
    w[int(y)][int(x)] = i
    r[i] = [int(y), int(x), D[z]]
crash = False
for _ in range(M):
    i, d, c = input().split()
    if not crash:
        crash = solve(int(i), d, int(c))
if not crash:
    print("OK")




참고



반응형