반응형

[광고 누르면 오늘의 행운 상승!!]

시뮬레이션 + dfs 문제 

바라보는 방향과 로봇청소기의 방향을 따로 생각해야한다.
후진할때 cnt를 안 빼줘서 계속 헤맸음.

package Study0227;

import java.util.*;
import java.io.*;

public class 로봇청소기 {
	static final int[] dx = {-1,0,1,0};
	static final int[] dy = {0,1,0,-1};
	static int N,M,ans;
	static int map[][];
	static boolean visit[][];
	static int cnt = 0;
	
	public static void main(String[] args) throws Exception {
		System.setIn(new FileInputStream("test.txt"));
		Scanner sc = new Scanner(System.in);
		
		N = sc.nextInt();
		M = sc.nextInt();
		
		int row = sc.nextInt();
		int col = sc.nextInt();
		int dir = sc.nextInt();
		map = new int[N][M];
		
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
				map[i][j] = sc.nextInt();
			}
		}
		
		clean(row,col,dir);
		System.out.println(cnt);
	}
	public static void clean(int row , int col, int dir) {
		int check = 0;
		map[row][col] = 2;
		
		cnt++; //현재위치 청소
		
		for (int i = 0; i < 4; i++) {
			int nowdir = (dir +3)%4 - i; //현재 방향의 왼쪽부터 탐색
			if(nowdir < 0) nowdir = (nowdir+4)%4;
			
			int nx = row + dx[nowdir];
			int ny = col + dy[nowdir];
			
			if((nx >= 0 || ny < N || ny >= 0 || ny < M)
					&& map[nx][ny] == 0 ) {
				//벽이 아닐 때
				clean(nx,ny,nowdir);
				return;
			}
			
			check++;
		}
		if(check == 4) { //4방향을 모두 조사했는데 벽이당
			int nowdir = (dir + 2)%4;
			int nx = row + dx[nowdir];
			int ny = col + dy[nowdir];
			if((nx >= 0 || ny < N || ny >= 0 || ny < M) 
					&& map[nx][ny] == 2) {
				cnt--;
				clean(nx,ny,dir);
				return;
			}
			return;
		}
	}
}
반응형

+ Recent posts