티스토리 뷰

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

 

14503번: 로봇 청소기

로봇 청소기가 주어졌을 때, 청소하는 영역의 개수를 구하는 프로그램을 작성하시오. 로봇 청소기가 있는 장소는 N×M 크기의 직사각형으로 나타낼 수 있으며, 1×1크기의 정사각형 칸으로 나누어져 있다. 각각의 칸은 벽 또는 빈 칸이다. 청소기는 바라보는 방향이 있으며, 이 방향은 동, 서, 남, 북중 하나이다. 지도의 각 칸은 (r, c)로 나타낼 수 있고, r은 북쪽으로부터 떨어진 칸의 개수, c는 서쪽으로 부터 떨어진 칸의 개수이다. 로봇 청소기는 다음

www.acmicpc.net

#include<iostream>
#include<vector>
#include<utility>

using namespace std;

vector<vector<int>> map;
int direct[4][2] = { {-1,0},{0,1},{1,0},{0,-1} };
int result = 0;
int N, M;		//맵 크기
int r, c, d;	//로봇좌표(r, c) , 바라보는 방향 d (0=북, 1=동, 2=남, 3=서)

void solution() {
	pair<pair<int, int>, int> now = make_pair(make_pair(r, c), d);

	while (1) {
		if(map[now.first.first][now.first.second] == 0){
			map[now.first.first][now.first.second] = 2;		//청소한 곳은 2 로 표시
			result++;
		}

		pair<pair<int, int>, int> temp = now;

		//각 방향 탐색
		for (int i = 0; i < 4; i++) {
			now.second = (now.second + 3) % 4;	//현재방향 기준 왼쪽으로 회전
			int y = now.first.first + direct[now.second][0];
			int x = now.first.second + direct[now.second][1];

			if (0 <= y && y < N && 0 <= x && x < M) {
				if (map[y][x] == 0) {
					now = make_pair(make_pair(y, x), now.second);
					break;
				}
			}
		}

		//네 방향 모두 청소 되었거나 벽이라면
		if (now == temp) {
			int y = now.first.first + direct[(now.second + 2) % 4][0];			//뒤로이동
			int x = now.first.second + direct[(now.second + 2) % 4][1];	//뒤로이동

			if(0 <= y && y < N && 0 <= x && x < M) {
				if (map[y][x] == 1)
					return;
				else {
					now = make_pair(make_pair(y, x), now.second);
				}
			}
		}
	}
}

int main(void) {
	cin >> N >> M;
	cin >> r >> c >> d;

	//맵 입력
	for (int i = 0; i < N; i++) {
		vector<int> v;
		for (int j = 0; j < M; j++) {
			int temp;
			cin >> temp;
			v.push_back(temp);
		}
		map.push_back(v);
	}

	solution();

	cout << result << endl;
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함