티스토리 뷰

728x90
반응형
문제 링크

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

 

14503번: 로봇 청소기

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

www.acmicpc.net

문제 풀이

문제 설명에 맞게 시물레이션 해서 풀면 되는 문제입니다.

알고리즘 관련 배경지식보다는 구현력이 중요한 문제라는 생각이 듭니다. 

소스 코드

 

import java.util.*;

public class Main {
	static int [] dx = { -1 , 0 , 1, 0};
	static int [] dy = { 0 , 1 , 0 , -1};
	static int N;
	static int M;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		N = sc.nextInt();
		M = sc.nextInt();
		int ans = 0;
		int r = sc.nextInt();
		int c = sc.nextInt();
		int way = sc.nextInt();


		int [][] map =  new int [N][M];

		for (int i = 0; i < map.length; i++) {
			for (int j = 0; j < map[0].length; j++) {
				map[i][j] = sc.nextInt();
			}
		}

		int cnt=0;
		while(true) {
			if(map[r][c] ==0) {
				map [r][c] = 2;
				ans ++;
			}
			int nr ;
			int nc ;
			if(cnt ==4 ) {

				nr = r+dx[((way-2)%4+4)%4];
				nc = c+dy[((way-2)%4+4)%4];

				if(!isRange(nr,nc) || map[nr][nc]==1) {
					break;
				}else {
					cnt =0;
					r = nr;
					c = nc;
					continue;
				}
			}

			nr = r+dx[((way-1)%4+4)%4];
			nc = c+dy[((way-1)%4+4)%4];

			if(!isRange(nr,nc)) {
				cnt ++;
				way --;
				continue;
			}
			if(map[nr][nc]==0) {
				cnt =0;
				r = nr;
				c = nc;
				way = (way+4-1)%4;
				continue;
			}else {
				cnt ++;
				way --;
				continue;
			}
		}
		System.out.println(ans);
	}

	static boolean isRange(int r , int c) {
		if(r<0 || c<0 || r>=N || c>=M)return false;
		return true;
	}
}

 

728x90
반응형
250x250
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   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
글 보관함