뚱땅뚱땅

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

알고리즘/백준

[문제] 백준 14503번 로봇 청소기

양순이 2021. 2. 15. 20:23
728x90

www.acmicpc.net/problem/14503

 

14503번: 로봇 청소기

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

www.acmicpc.net

풀이

 

방향전환만 헷갈리지 않으면 쉽게 풀 수 있다.

public class BOJ_14503 {
	static int[] dx = { -1, 0, 1, 0 }; // 북동남서
	static int[] dy = { 0, 1, 0, -1 };

	static int[][] matrix;	// 
	static int N,M;
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(in.readLine(), " ");
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());

		st = new StringTokenizer(in.readLine(), " ");
		int x = Integer.parseInt(st.nextToken()); // 현재 위치
		int y = Integer.parseInt(st.nextToken());
		int d = Integer.parseInt(st.nextToken()); // 현재 방향

		// init matrix
		matrix = new int[N][M];
		for (int i = 0; i < N; i++) {
			st = new StringTokenizer(in.readLine(), " ");
			for (int j = 0; j < M; j++) {
				matrix[i][j] = Integer.parseInt(st.nextToken());
			}
		}
		
		int sum = 1;
		matrix[x][y] = 2;	// 현재 위치 청소
		boolean stop = false;	// 더 이상 청소가 불가능하다면  stop = true
		
		while (!stop) {
			if (!canClean(x, y)) { // 청소할 곳이 없다면
				int nx = x - dx[d]; // 방향 유지한 채로 후진한 칸
				int ny = y - dy[d];
				if (matrix[nx][ny] == 1) { // 한 칸 후진한 곳이 벽이라면
					stop = true; // 멈춤
					break;
				} else {	// 한칸 후진
					x = nx;
					y = ny;
				}
			} 
			// 4방향 중 청소할 곳이 있을 경우
			else {
				d = (d + 3) % 4; // 현재 방향의 왼쪽 방향
				int nx = x + dx[d];
				int ny = y + dy[d];
				// 왼쪽 방향이 영역 내부에 있고 아직 청소 전이라면
				if (nx >= 0 && nx < N && ny >= 0 && ny < M && matrix[nx][ny] == 0) {
					x = nx;	// 왼쪽으로 이동
					y = ny; 
					sum++;	// 청소한 영역 수 증가
					matrix[x][y] = 2;	// 청소 처리
				}

			}
		}
		System.out.println(sum);	// 청소한 영역의 개수
	}
// 현재 위치에서 동서남북 방향에 청소할 곳이 있는지 확인하는 함수
	static boolean canClean(int a, int b) {
		for (int dir = 0; dir < 4; dir++) {
			int nx = a + dx[dir];
			int ny = b + dy[dir];
			if (matrix[nx][ny] == 0)
				return true;
		}
		return false;
	}
}
728x90
Comments