안녕하세요

여행벌입니다.

오늘은 ACM-ICPC 2016 본선 문제인

BOJ 13567번 ROBOT 문제풀이를 해보겠습니다.


[문제파악]

1. (0,0) 위치에서 시작하여 로봇이 주어진 명령에 따라 이동을 한다.

2. 이동 과정에서 주어진 MAP을 벗어난다면, "-1"을 출력하고 아니라면 로봇의 최종 위치를 출력한다.

 

[알고리즘설계]

1. 현재 로봇의 위치를 x , y 변수에 저장하고, 로봇이 현재 향하고 있는 방향을 direction 변수에 담아주자.

direction 에 0(오) 1(왼) 2(위) 3(아래)를 저장한다.

- TURN 명령은 오른쪽으로 90도 회전, 왼쪽으로 90도 회전 2가지 종류가 있고, direction 변수를 TURN에 맞춰서 새롭게 저장해준다.

- MOVE는 direction이 가리키는 방향으로 이동하며 x , y 변수를 새롭게 저장해준다.

2. 명령을 수행하는 과정에서 MAP을 벗어나는지 체크해주고 벗어난다면 "-1"을 출력하고, 아니라면 명령을 다 수행하고 위치를 출력해준다.

 

[주의할점]

1. 명령을 하나씩 받으면서 로봇을 이동시켜주려 한다면 중간에 MAP을 벗어나는 상황이 생겨도 일단 명령 입력을 다 받아야 하므로 종료하면 안 된다.

따라서, 명령을 다 입력받고 로봇을 이동시키는 것이 더 편하다.

#include<stdio.h>
#include<string.h>

char instruction1[1000][5];
int instruction2[1000];

/* direction 에 0(오) 1(왼) 2(위) 3(아래)를 저장한다.*/
int main(void) {
	int length, ninstruction, x = 0, y = 0, direction = 0;
	scanf("%d %d", &length, &ninstruction);

	for (int i = 0; i < ninstruction; i++) {
		scanf("%s %d", instruction1[i], &instruction2[i]);
	}

	for (int i = 0; i < ninstruction; i++) {
		if (strcmp(instruction1[i], "TURN") == 0) {
			// 왼쪽으로 90도 회전
			if (instruction2[i] == 0) {
				if (direction == 0) {
					direction = 2;
				}
				else if (direction == 1) {
					direction = 3;
				}
				else if (direction == 2) {
					direction = 1;
				}
				else if (direction == 3) {
					direction = 0;
				}
			}
			// 오른쪽으로 90도 회전
			else if (instruction2[i] == 1) {
				if (direction == 0) {
					direction = 3;
				}
				else if (direction == 1) {
					direction = 2;
				}
				else if (direction == 2) {
					direction = 0;
				}
				else if (direction == 3) {
					direction = 1;
				}
			}
		}
		else if (strcmp(instruction1[i], "MOVE") == 0) {
			if (direction == 0) {
				for (int j = 0; j < instruction2[i]; j++) {
					x++;
				}
			}
			else if (direction == 1) {
				for (int j = 0; j < instruction2[i]; j++) {
					x--;
				}
			}
			else if (direction == 2) {
				for (int j = 0; j < instruction2[i]; j++) {
					y++;
				}
			}
			else if (direction == 3) {
				for (int j = 0; j < instruction2[i]; j++) {
					y--;
				}
			}
		}
		if(x < 0 || x > length || y < 0 || y > length){
			printf("%d", -1);
			return 0;
		}
	}
	printf("%d %d", x, y);
	return 0;
}

 

+ Recent posts