슈콩

[BOJ] 14503 로봇 청소기 본문

Algorithms/Baekjoon

[BOJ] 14503 로봇 청소기

shukong 2025. 11. 29. 23:50

 

 

[문제]

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

 

 

[소스 코드]

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

public class Main {
	static int[] dr = {-1,0,1,0};
	static int[] dc = {0,1,0,-1};
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken());
		int m = Integer.parseInt(st.nextToken());
		st = new StringTokenizer(br.readLine());
		int currR = Integer.parseInt(st.nextToken());
		int currC = Integer.parseInt(st.nextToken());
		int currDir = Integer.parseInt(st.nextToken());
		int[][] map = new int[n][m];
		for(int i=0;i<n;i++) {
			st = new StringTokenizer(br.readLine());
			for(int j=0;j<m;j++) {
				map[i][j] = Integer.parseInt(st.nextToken());
			}
		}
		int result = 0;
		out:
		while(true) {
			if(map[currR][currC]==0) { 
				map[currR][currC] = 2;
				result++;
			}
			int cnt = 0;
			for(int d=0;d<4;d++) {
				int nr = currR + dr[d];
				int nc = currC + dc[d];
				if(nr<0 || nr>=n || nc<0 || nc>=m) continue;
				if(map[nr][nc]==0) {
					cnt++;
				}
			}
			if(cnt>0) {
				for(int i=0;i<4;i++) {
					currDir = (currDir+3) % 4;
					int nr = currR + dr[currDir];
					int nc = currC + dc[currDir];
					if(nr<0 || nr>=n || nc<0 || nc>=m) continue;
					if(map[nr][nc]==0) {
						currR = nr;
						currC = nc;
						break;
					}
				}
			}
			else {
				int nr = currR + dr[(currDir+2)%4];
				int nc = currC + dc[(currDir+2)%4];
				if(nr<0 || nr>=n || nc<0 || nc>=m || map[nr][nc]==1) break out;
				if(map[nr][nc]!=1) {
					currR += dr[(currDir+2)%4];
					currC += dc[(currDir+2)%4];
				}
			}
		}
		System.out.println(result);
	}
}

'Algorithms > Baekjoon' 카테고리의 다른 글

[BOJ] 12100 2024(Easy)  (0) 2025.11.30
[BOJ] 13460 구슬 탈출 2  (0) 2025.11.30
[BOJ] 9205 맥주 마시면서 걸어가기  (0) 2025.11.29
[BOJ] 2573 빙산  (0) 2025.11.28
[BOJ] 2468 안전 영역  (0) 2025.11.28