hotamul의 개발 이야기

[Algorihtm][C++] JUNGOL 4199. swat 로봇청소기 본문

myt-algorithm-practice/Samsung SW Certi Adv

[Algorihtm][C++] JUNGOL 4199. swat 로봇청소기

hotamul 2021. 11. 1. 19:45

url: http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=3549&sca=99 

 

JUNGOL

 

www.jungol.co.kr

기존에 풀었던 백준 문제와 동일한 문제이다. (https://hotamul.tistory.com/18)

기존에는 함수로 단순하게 구현했는데 뭔가 Class 처럼? (실제로 class를 만들어 풀지는 않았지만) 구현하고 싶어 struct ROBOT에 cleaning, left_turn, move, back_move 함수를 넣어 robot의 기능처럼 사용했다. 훨씬 가독성이 좋아진 느낌이다.

 

코드

#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <queue>
using namespace std;

int R, C;
int map[50][50];
bool visit[50][50];
const int dy[] = { -1,0,1,0 };
const int dx[] = { 0,1,0,-1 };

struct ROBOT {
	int y, x, d;
	int clean;

	void cleaning() { // 현재 공간이 청소되어 있지 않으면 청소해라
		if (visit[y][x] == 0) {
			++clean;
			visit[y][x] = true;;
		}
	}

	void left_turn() { // 반시계 방향으로 돌아라
		d = (d + 3) % 4;
	}

	int is_move_okay(int r, int c, int type) { // type (1: 앞, -1: 뒤)
		int ret = 0;
		if (type == 1) {
			if (r >= 0 && r < R && c >= 0 && c < C && !visit[r][c] && !map[r][c]) {
				ret = 1;
			}
		}
		else {
			if (r >= 0 && r < R && c >= 0 && c < C && !map[r][c]) {
				ret = 1;
			}
		}
		return ret;
	}

	int move() { // 앞으로 움직였다면 1 return
		int ret = 0;
		int ny = y + dy[d];
		int nx = x + dx[d];
		if (is_move_okay(ny, nx, 1)) {
			y = ny, x = nx;
			ret = 1;
		}
		return ret;
	}

	int back_move() { // 뒤로 움직였다면 1 return
		int ret = 0;
		int ny = y - dy[d];
		int nx = x - dx[d];
		if (is_move_okay(ny, nx, -1)) {
			y = ny, x = nx;
			ret = 1;
		}
		return ret;
	}
};
ROBOT robot;

int solve() {
	int ret = 0;
	bool flag = true; // 종료 여부 확인하는 flag
	while (flag) {
		robot.cleaning();
		int count;
		for (count = 0; count < 4; count++) {
			robot.left_turn();
			if (robot.move()) {
				break;
			}
		}
		if (count == 4) { // 다시 원래 방향으로 돌아옴
			if (robot.back_move()) { // 뒤로 갈 수 있으면 계속 진행
				continue;
			}
			else { // 그렇지 않으면 종료
				flag = false;
			}
		}
	}

	ret = robot.clean; // 청소한 횟 수 return;
	return ret;
}

int main() {
	scanf("%d %d", &R, &C);
	scanf("%d %d %d", &robot.y, &robot.x, &robot.d);
	for (int r = 0; r < R; r++) {
		for (int c = 0; c < C; c++) {
			scanf("%d", &map[r][c]);
		}
	}
	int ans = solve();
	printf("%d", ans);
	return 0;
}

 

Comments