Notice
Recent Posts
Recent Comments
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

코린이 탈출기

[백준 14503] 로봇 청소기 본문

문제 풀이/BFS

[백준 14503] 로봇 청소기

명란파스타 2020. 7. 18. 16:44

문제 바로가기

 

14503번: 로봇 청소기

로봇 청소기가 주어졌을 때, 청소하는 영역의 개수를 구하는 프로그램을 작성하시오. 로봇 청소기가 있는 장소는 N×M 크기의 직사각형으로 나타낼 수 있으며, 1×1크기의 정사각형 칸으로 나누어

www.acmicpc.net

 

삼성 역량테스트 기출 문제를 풀어보았다

어렵지는 않은데 까다로운 문제..

국어도 잘해야 빨리 풀 수 있을 것 같다

 

나는 동이랑 서 방향을 헷갈려서 거기서 오래걸렸다

헷갈리기 시작하면 끝도 없으니까 한 방에 제대로 이해하고 풀어야겠다

 

 

#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>

using namespace std;

int N, M;
int visited[50][50];
int map[50][50];
pair<int, int> start;
int dir;//0은 북, 1은 동, 2는 남, 3은 서
int pos[4][2] = { {-1,0}, {0, 1}, {1,0}, {0,-1} };
int clean_cnt;

void bfs(int x, int y)
{
	queue<pair<int, int>> Q;

	Q.push(make_pair(x, y));
	visited[y][x] = 1;
	clean_cnt++;

	while (!Q.empty())
	{
		int cx = Q.front().first;
		int cy = Q.front().second;
		Q.pop();

		int cnt = 0;
		while (1)
		{
			cnt++;
			int new_dir = (dir - 1);
			if (new_dir == -1)
				new_dir = 3;

			int nx = cx + pos[new_dir][1];
			int ny = cy + pos[new_dir][0];

			if (!map[ny][nx] && !visited[ny][nx]) //a 경우
			{
				visited[ny][nx] = 1;
				Q.push(make_pair(nx, ny));
				dir = new_dir;
				clean_cnt++;
				break;
			}

			if (cnt == 4)
			{
				nx = cx - pos[new_dir][1];
				ny = cy - pos[new_dir][0];

				if (map[ny][nx] == 1)//후진 못하는 경우(d)
				{
					return;
				}
				else
				{
					Q.push(make_pair(nx, ny));
					dir = new_dir;
					break;
				}
			}
			dir = new_dir;
		}
	}
}

int main()
{
	cin >> N >> M;

	cin >> start.second >> start.first;

	cin >> dir;

	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < M; j++)
		{
			cin >> map[i][j];
		}
	}

	bfs(start.first, start.second);

	cout << clean_cnt << endl;

	return 0;
}

'문제 풀이 > BFS' 카테고리의 다른 글

[백준 15686] 치킨 배달  (0) 2020.07.29
[백준 2573] 빙산  (2) 2020.07.17