https://www.acmicpc.net/problem/14503
import java.io.*;
import java.util.*;
public class Main {
public static int N, M, ans = 0, r, c, d;
public static int[][] map, visited;
public static int[] dr = {-1, 0, 1, 0};
public static int[] dc = {0, 1, 0, -1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
// 1. 입력받기
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
map = new int[N][M];
visited = new int[N][M];
st = new StringTokenizer(br.readLine());
r = Integer.parseInt(st.nextToken());
c = Integer.parseInt(st.nextToken());
d = Integer.parseInt(st.nextToken());
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());
if(map[i][j] == 1) visited[i][j] = 1;
}
}
while(true){
// 현재칸이 아직 청소되지 않은경우;
if(visited[r][c] == 0) {
visited[r][c] = 1;
ans++;
}
// 주변 4칸 검사
int cnt = 0;
for(int d = 0; d < 4; d++){
int nr = r + dr[d];
int nc = c + dc[d];
if(nr < 0 || nr >= N || nc < 0 || nc >= M || visited[nr][nc] == 1) continue;
cnt++;
}
// 현재 칸의 주변 4칸 중 청소되지 않은 빈 칸이 없는 경우
if(cnt == 0) {
// 바라보는 방향을 유지한 채로 한 칸 후진할 수 있다면 한 칸 후진하고 1번으로 돌아간다.
r += dr[(d + 2) % 4];
c += dc[(d + 2) % 4];
// 바라보는 방향의 뒤쪽 칸이 벽이라 후진할 수 없다면 작동을 멈춘다.
if(map[r][c] == 1) break;
} else { // 현재 칸의 주변 4칸 중 청소되지 않은 빈 칸이 있는 경우
while(true){
// 반시계 방향으로 90도 회전한다.
d = (d + 3) % 4;
// 바라보는 방향을 기준으로 앞쪽 칸이 청소되지 않은 빈 칸인 경우 한 칸 전진한다.
int nr = r + dr[d];
int nc = c + dc[d];
if(visited[nr][nc] == 0) {
r = nr;
c = nc;
break;
}
}
}
}
System.out.println(ans);
}
}
잘풀고 실수때문에 계속 틀린 문제
r += dr[(d + 2) % 4];
실수한 부분은 이부분이였다.
r += dr[(d + 2) % 2]; 로 실수했다.
'코딩테스트 > JAVA' 카테고리의 다른 글
| [백준 JAVA] 15686번: 치킨배달 (0) | 2025.10.02 |
|---|---|
| [백준 JAVA] 14719번: 빗물 (0) | 2025.10.02 |
| [백준 JAVA] 12865번: 평범한 배낭 (0) | 2025.10.01 |
| [백준 JAVA] 11725번: 트리의 부모 찾기 (0) | 2025.10.01 |
| [백준 JAVA] 11660번: 구간 합 구하기 5 (0) | 2025.10.01 |