본문 바로가기
알고리즘/구현

백준 14503번 : 로봇 청소기

by Jason95 2021. 1. 10.

문제 링크 : www.acmicpc.net/problem/14503

내 풀이(2021.1.10) : 

#include <iostream>

using namespace std;

int N, M;
int map[50][50]; // [y][x]
int visit[50][50]; // [y][x]
int _left[4][2] = {
	{ 0, -1}, // 북쪽
	{-1,  0}, // 동쪽
	{ 0,  1}, // 남쪽
	{ 1,  0}, // 서쪽
};
int back[4][2] = {
	{ 1,  0}, // 북쪽
	{ 0, -1}, // 동쪽
	{-1,  0}, // 남쪽
	{ 0,  1}, // 서쪽
};

void show_map() {
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < M; j++) {
			cout << (map[i][j] || visit[i][j]) << " ";
		}
		cout << endl;
	}
	cout << endl;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> N >> M;
	int r, c, d; cin >> r >> c >> d;
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < M; j++) {
			cin >> map[i][j];
		}
	}

	int cnt = 0;
	bool stop = false;
	while (true) {
		//cout << "(r,c) = " << "(" << r << "," << c << ")" << endl;
		if (visit[r][c] == 0) {
			visit[r][c] = 1; cnt++;
			//show_map();
		}
		int dup = 4;
		while (true) {
			int y = r + _left[d][0]; int x = c + _left[d][1];
			if (map[y][x] == 0 && visit[y][x] == 0) {
				r += _left[d][0]; c += _left[d][1];
				d -= 1; if (d < 0) d += 4;
				break;
			}
			else {
				d -= 1; if (d < 0) d += 4;
				//cout << "(r,c) = " << "(" << r << "," << c << ")" << " dup = " << dup << " d = " << d << endl;
				if (--dup == 0) {
					dup = 4;
					int y = r + back[d][0]; int x = c + back[d][1];
					if (map[y][x] == 1) {
						stop = true;
						break;
					}
					else {
						r += back[d][0]; c += back[d][1];
						continue;
					}
				}
				continue;
			}
		}
		if (stop) break;
	}
	
	cout << cnt;

	return 0;
}

바라보는 방향에 따른 예상 이동 위치를 나타내는 다음과 같은 변수들은

int _left[4][2] = {
	{ 0, -1}, // 북쪽
	{-1,  0}, // 동쪽
	{ 0,  1}, // 남쪽
	{ 1,  0}, // 서쪽
};
int back[4][2] = {
	{ 1,  0}, // 북쪽
	{ 0, -1}, // 동쪽
	{-1,  0}, // 남쪽
	{ 0,  1}, // 서쪽
};

다음과 같이 표현하는 것도 가능하다.

int left_dy[4] = { 0, -1, 0, 1 }; // 북동남서
int left_dx[4] = { -1, 0, 1, 0 }; // 북동남서
int back_dy[4] = { 1, 0, -1, 0 }; // 북동남서
int back_dx[4] = { 0, -1, 0, 1 }; // 북동남서