백준 14503 C++ 로봇청소기

2023. 9. 15. 14:05알고리즘

문제는 단순 구현 문제였다. 예제 2번에 대한 답이 계속해서 나오지 않아 고민했는데,

'바라보는 방향의 뒤쪽 칸이 벽이면 후진할 수 없다' 라는 것을 기억해야한다.

즉 청소한 칸의 경우는 후진할 수 있다.

이 부분을 없애니 바로 맞았다.

 

#include <iostream>
#include <cstring>

using namespace std;

int N, M, cnt;
int room[51][51];

int dx[4] = { 0, 1, 0, -1 };
int dy[4] = { -1, 0, 1, 0 };
int x, y, dir;


int move(void) {
	int nx, ny;
	if (room[y][x] == 0) { // 청소가 되어 있지 않으면 청소한다
		room[y][x] = 2;
		cnt++;
		return 1;
	}
	for (int i = 1;i <= 4;i++) { 
		int newDir = (dir - i);
		if (newDir < 0) newDir += 4;
		ny = y + dy[newDir];
		nx = x + dx[newDir];
		if (nx < 0 || ny < 0 || nx >= M || ny >= N) {
			continue;
		}
		if (room[ny][nx] == 0) {
			y = ny;
			x = nx;
			dir = newDir;
			return 1;
		}
	}
	// 청소할 곳이 없다
	ny = y + dy[(dir + 2) % 4];
	nx = x + dx[(dir + 2) % 4];
	if (nx < 0 || ny < 0 || nx >= M || ny >= N || room[ny][nx] == 1 ) {
		return 0;
	}
	else {
		y = ny, x = nx;
		return 1;
	}
}
int main(void) {
	cin.tie(NULL);
	ios::sync_with_stdio(false);
	cin >> N >> M;

	cin >> y >> x >> dir;
	for (int i = 0;i < N;i++) {
		for (int j = 0;j < M;j++) {
			cin >> room[i][j];
		}
	}
	while (1) {
		if (move() == 0) {
			break;
		}
	}
	cout << cnt << endl;
	return 0;
}

실제로 코딩테스트 볼 때 이렇게 문제 조건이 명확하지 않은 경우가 종종 있다고 하는데 이런 부분들을 어떻게 알 수 있을까 걱정이 된다 

'알고리즘' 카테고리의 다른 글

프로그래머스 모음사전 C++ dfs  (0) 2023.09.17
프로그래머스 리코쳇 로봇 C++  (0) 2023.09.17
백준 14500 테트로미노 c++ (dfs)  (0) 2023.09.01
후...  (0) 2023.08.29
백준 16234 인구이동 C++  (0) 2023.08.23