문제 링크입니다: https://www.acmicpc.net/problem/14503
14503번: 로봇 청소기
로봇 청소기가 주어졌을 때, 청소하는 영역의 개수를 구하는 프로그램을 작성하시오. 로봇 청소기가 있는 장소는 N×M 크기의 직사각형으로 나타낼 수 있으며, 1×1크기의 정사각형 칸으로 나누어져 있다. 각각의 칸은 벽 또는 빈 칸이다. 청소기는 바라보는 방향이 있으며, 이 방향은 동, 서, 남, 북중 하나이다. 지도의 각 칸은 (r, c)로 나타낼 수 있고, r은 북쪽으로부터 떨어진 칸의 개수, c는 서쪽으로 부터 떨어진 칸의 개수이다. 로봇 청소기는 다음
www.acmicpc.net
흥미로운 문제였습니다.
핵심은 네 방향 다 청소할 곳이 없을 때 이미 청소한 곳이여도 돌아올 수 있다는 것이였습니다.
또한, 로봇의 시야는 1이기 때문에 거리가 2 이상인 곳이 청소되어 있지 않다고 해도 거리가 1인 곳이 청소가 되어있다면 전진할 수가 없습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <queue> | |
#include <vector> | |
#include <algorithm> | |
using namespace std; | |
const int MAX = 50; | |
typedef struct | |
{ | |
int y, x; | |
}Dir; | |
Dir moveDir[4] = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; // N E S W | |
int N, M; | |
int graph[MAX][MAX]; | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
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 >> graph[i][j]; | |
int result = 0; | |
queue<pair<pair<int, int>, int>> q; | |
q.push({ {r, c}, d }); | |
while (!q.empty()) | |
{ | |
int y = q.front().first.first; | |
int x = q.front().first.second; | |
int dir = q.front().second; | |
if (graph[y][x] == 0) | |
{ | |
//벽과 구분 위해 | |
graph[y][x] = 2; | |
result++; | |
} | |
q.pop(); | |
bool flag = false; | |
for (int i = 0; i < 4; i++) | |
{ | |
//좌회전을 위해 모듈러 연산 | |
int nextDir = (dir + (3 - i)) % 4; | |
int nextY = y + moveDir[nextDir].y; | |
int nextX = x + moveDir[nextDir].x; | |
if(0<=nextY && nextY < N && 0 <= nextX && nextX < M) | |
if (!graph[nextY][nextX]) | |
{ | |
q.push({ {nextY, nextX}, nextDir}); | |
flag = true; | |
break; | |
} | |
} | |
//네 방향 다 청소되어 있는 경우 | |
if (!flag) | |
{ | |
int beforeY = y - moveDir[dir].y; | |
int beforeX = x - moveDir[dir].x; | |
if ((0 <= beforeY && beforeY < N && 0 <= beforeX && beforeX < M) && graph[beforeY][beforeX] != 1) | |
q.push({ {beforeY, beforeX}, dir }); | |
else | |
break; | |
} | |
} | |
cout << result << "\n"; | |
return 0; | |
} | |


지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
백준 14499번 주사위 굴리기 (0) | 2019.04.30 |
---|---|
백준 5373번 큐빙 (0) | 2019.04.29 |
백준 15662번 톱니바퀴(2) (0) | 2019.04.27 |
백준 16235번 나무 재테크 (2) | 2019.04.14 |
백준 16236번 아기 상어 (2) | 2019.04.10 |