14503번: 로봇 청소기

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

www.acmicpc.net

 

 

 


 

 

 

 

  • 내용

NxM 크기의 직사각형의 공간을 로봇 청소기가 청소할 수 있다. 각각의 칸은 벽 또는 빈칸이다. 청소기는 동, 서, 남, 북으로 바라보는 방향이 있다.
지도의 각 칸은 (r,c)로 나타낼 수 이쏙, r은 북쪽으로부터 떨어진 칸의 개수, c는 서쪽으로 부터 떨어진 칸의 개수이다.

로봇 청소기는 이미 청소되어있는 칸을 또 청소하지 않으며, 벽을 통과할 수 없다.
로봇 청소기의 작동 방법은 다음과 같다.
1. 현재 위치를 청소한다.
2. 현재 위치에서 현재 방향을 기준으로 왼쪽방향부터 차례대로 탐색을 진행한다.
   a. 왼쪽 방향에 아직 청소하지 않은 공간이 존재한다면, 그 방향으로 회전한 다음 한 칸을 전진하고 1번부터 진행한다.
   b. 왼쪽 방향에 청소할 공간이 없다면, 그 방향을 ㅗ회전하고 2번으로 돌아간다.
   c. 네 방향 모두 청소가 이미 되어있거나 벽인 경우에는, 바라보는 방향을 유지한 채로 한 칸 후진을 하고 2번으로 돌       아간다.
   d. 네 방향 모두 청소가 이미 되어있거나 벽이면서, 뒤쪽 방향이 벽이라 후진도 할 수 없는 경우에는 작동을 멈춘다.


 

 

 

  • 생각

 

queue를 이용해서 풀면 쉽게 풀 수 있을 것 같다. queue로 현재 위치와 방향을 offer해가면서 이동 가능할때만 queue에 넣고 4방향 모두 가지못할땐 뒤의 방향이 벽인지 확인해주고 벽이 아니면 queue에 offer, 벽이면 종료

 

 

 

 

  • 코드

 

import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
	static int[] x =  { -1, 0, 1, 0 };
    static int[] y = { 0, 1, 0, -1 };
	static int[][] array;
	static Queue<int[]> queue;
	static int N, M, answer;

	public static void main(String[] args) throws Exception {
		SetData();
		System.out.println(answer);
	}

	// 데이터
	private static void SetData() throws Exception {
		InputReader in = new InputReader(System.in);

		N = in.nextInt();
		M = in.nextInt();
		array = new int[N][M];
		queue = new LinkedList<>();
		queue.offer(new int[] {in.nextInt(), in.nextInt(), in.nextInt()});
		answer = 1;

		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				array[i][j] = in.nextInt();
			}
		}

		OperateRobot();
	}

	private static void OperateRobot() {
		while (!queue.isEmpty()) {
			int[] robot = queue.poll();
			int robotX = robot[0];
			int robotY = robot[1];
			int d = robot[2];
			// 청소
			array[robotX][robotY] = 2;

            boolean check = false;    // 4 방향 모두 갈 수 없을 때
            int r;
            int c;
            int nextD;
 
            for (int i = 0; i < 4; i++) {
                d = (d + 3) % 4;    
                r = robotX + x[d];    
                c = robotY + y[d];    

                if (r < 0 || c < 0 || r >= N || c >= M)   continue;
                
                //다음 이동할 위치가  청소되지 않은 곳이라면 간다.
                if (array[r][c] == 0) {
                    queue.add(new int[] {r,c, d});
        			answer++;
                    check = true;
                    break;
                }
            }
            
            // 네 방향 모두 청소됐거나 벽일 경우 후진
            if (!check) {
                nextD = (d + 2) % 4;
                r = robotX + x[nextD];
                c = robotY + y[nextD];
 
                // 후진을 못할 경우
                if (array[r][c] != 1) {
                    queue.add(new int[] {r, c, d});
                }
            }

		}
	}
}

class InputReader {
	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

+ Recent posts