[백준] 14503번 로봇 청소기 (C++, 삼성 기출)

코딩은 많은 시행착오·2022년 3월 10일
0

swea

목록 보기
4/10

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

이 문제도 bfs를 통한 간단한 구현문제로 쉽게 풀 수 있었다! (실력이 느는 걸지도)
문제를 따라 구현하니 문제가 풀렸다.
단, 청소기의 방향에 따라 바꿔주는 부분에서 왼쪽 방향으로 이동하면 (현재 방향 + 3) % 4 를 해줬고, 뒤쪽 방향으로 이동하면 (현재 방향 + 2) % 4 를 해줘서 해결할 수 있었다.

  1. 현재 청소기의 좌표, 방향을 queue에 넣는다.
  2. 현재 방향 기준으로 왼쪽 방향좌표를 구한다.
  3. 소하지 않은 곳이면 map에 2를 넣어주고, queue에 새로운 좌표와 방향을 넣고 결과 값 +1을 해준다.
  4. 청소한 곳이거나 이면 청소기의 방향을 새로 구한 방향으로 변경해준다.
  5. 4방향을 탐색했을 때, 청소기가 움직이지 않았으면 청소기 기준으로 뒤쪽 방향으로 이동한다.
    5-1. 뒤쪽이 벽이거나 map을 넘어가면 탐색을 종료한다.
    5-2. 아니면 queue에 이동한 좌표와 현재 방향을 넣어준다.
  6. 2번으로 돌아가 반복한다.
#include <iostream>
#include <queue>

using namespace std;

int n, m, r, c, d;
int map[51][51];
int dir[4][2] = { {0, -1}, {1,0}, {0,1}, {-1,0} };
int ans = 0;

struct clean {
public :
	int x;
	int y;
	int dir;
	clean(int x, int y, int dir) {
		this->x = x;
		this->y = y;
		this->dir = dir;
	}
};

void move() {
	queue<clean> q;
	q.push(clean(c, r, d));
	map[r][c] = 2;
	ans++;
	while (!q.empty()) {
		clean cur = q.front();
		q.pop();
		bool is_move = false;
		for (int i = 0; i < 4; i++) {
			int n_dir = (cur.dir + 3) % 4;
			int nx = cur.x + dir[n_dir][0];
			int ny = cur.y + dir[n_dir][1];
			if (nx < 0 || nx > m || ny < 0 || ny > n) continue;
			if (map[ny][nx] == 0) {
				is_move = true;
				map[ny][nx] = 2;
				q.push(clean(nx, ny, n_dir));
				ans++;
				break;
			}
			else {
				cur.dir = n_dir;
			}
		}
		if (!is_move) {
			int n_dir = (cur.dir + 2) % 4;
			int nx = cur.x + dir[n_dir][0];
			int ny = cur.y + dir[n_dir][1];
			if (nx < 0 || nx > m || ny < 0 || ny > n || map[ny][nx] == 1) break;
			q.push(clean(nx, ny, cur.dir));
		}
	}
}

int main() {
	cin >> n >> m >> r >> c >> d;
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cin >> map[i][j];
	move();
	cout << ans;
}

0개의 댓글