본문 바로가기
Computer Science/Algorithms

로봇 청소기

by softserve 2021. 10. 31.
반응형

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

1. 개요

n x m 바닥에서 순회를 하는 문제입니다.

2. 고난과 역경

모든 문제 해결은 문제를 꼼꼼히 읽는 것에서 시작합니다.

문제를 잘못 이해한 죄로 한참을 헤맨 끝에 후진을 과소평가했다는 것을 깨닫게 되었습니다.

문제의 조건에 따르면 이 청소기는 '청소를 한 곳' 과 '벽' 을 구분할 수 있고,

사방에 청소할 곳이 없더라도 뒤가 벽으로 막힌 것이 아니라면 계속 후진하여 탈출이 가능합니다.

 

3. 코드

 

import java.util.*;

class Main {
    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       int n = sc.nextInt(), m = sc.nextInt();
       int[] pos = {sc.nextInt(), sc.nextInt()};
       int d = sc.nextInt();
       int[][] space = new int[n][m];
 
       for(int i = 0; i < n; i++) {
    	   for(int j = 0; j < m; j++) {
    		   space[i][j] = sc.nextInt();
    	   }
       }
       
       space[pos[0]][pos[1]] = 2;
       int count=1;
       int c=0;
       while(true) {
	       if(check(space, pos, d, true)>0) { // 왼쪽이 0 인지 확인
	    	  d = turnLeft(d); 
	    	  c++;
	    	  if(c==4) { // 4방향이 모두 0이 아님
		    	   if(check(space, pos, d, false)==1) break; // 뒤가 벽(1)인지 확인
		    	   else { //후진
		    		   d = turnAround(d);
		    		   move(pos, d);
		    		   c = 0;
		    		   d = turnAround(d);
		    	   }
		       }
	    	  continue;
	       }
	       
	       else { // 왼쪽이 0
	    	   d = turnLeft(d);
	    	   move(pos, d);
	    	   c = 0;
	    	   space[pos[0]][pos[1]] = 2; // 청소(2)
	    	   count++;
	       }
       }
       System.out.println(count);
       
    }
    public static int turnLeft(int d) {
    	if(d==0) d=3;
    	else d -= 1;
    	return d;
    }
    public static int turnAround(int d) {
    	d = (d + 2) % 4;
    	return d;
    }
    public static int check(int[][] s, int[]p, int d, boolean isLeft) {
    	
    	if(isLeft)	d = turnLeft(d);
    	else d = turnAround(d);
    	
    	if(d==0) return s[p[0]-1][p[1]];
    	else if(d==3) return s[p[0]][p[1]-1];
    	else if(d==2) return s[p[0]+1][p[1]];
    	else if(d==1) return s[p[0]][p[1]+1];
    	else return -1;
    }
    public static void move(int[] p, int d) {
    	
    	if(d==0) p[0]--; 
    	else if(d==3) p[1]--; 
    	else if(d==2)  p[0]++; 
    	else if(d==1)  p[1]++;    		    	
    }
}

 

반응형

'Computer Science > Algorithms' 카테고리의 다른 글

완전탐색 - 순열  (0) 2021.11.03
피보나치 함수 카운팅  (0) 2021.11.01
그래프의 탐색, bfs 와 dfs  (0) 2021.11.01
집합 - Set 구현하기  (0) 2021.11.01
방 번호 문제  (0) 2021.10.30

댓글