https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV4yLUiKDUoDFAUx
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Solution {
public static int T, R, C;
public static char[][] map;
public static boolean[][][][] visited;
public static int[] dr = { -1, 0, 1, 0 };
public static int[] dc = { 0, 1, 0, -1 };
public static Queue<int[]> q;
public static int wrapR(int r) {
return (r + R) % R;
}
public static int wrapC(int c) {
return (c + C) % C;
}
public static void move(int r, int c, int memory, int direction) {
int nr = wrapR(r + dr[direction]);
int nc = wrapC(c + dc[direction]);
if (!visited[nr][nc][memory][direction]) {
visited[nr][nc][memory][direction] = true;
q.offer(new int[] { nr, nc, memory, direction });
}
}
public static void bfs(int tc) {
q = new LinkedList<>();
q.offer(new int[] { 0, 0, 0, 1 });
visited[0][0][0][1] = true;
while (!q.isEmpty()) {
int[] cur = q.poll();
int r = cur[0];
int c = cur[1];
int memory = cur[2];
int direction = cur[3];
char cell = map[r][c];
if (cell == '@') {
System.out.println("#" + tc + " YES");
return;
}
switch (cell) {
case '<': direction = 3; break;
case '>': direction = 1; break;
case '^': direction = 0; break;
case 'v': direction = 2; break;
case '_': direction = (memory == 0) ? 1 : 3; break;
case '|': direction = (memory == 0) ? 2 : 0; break;
case '?':
for (int i = 0; i < 4; i++) move(r, c, memory, i);
continue;
case '+': memory = (memory + 1) % 16; break;
case '-': memory = (memory + 15) % 16; break;
default:
if (Character.isDigit(cell)) {
memory = cell - '0';
}
break;
}
move(r, c, memory, direction);
}
System.out.println("#" + tc + " NO");
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
T = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= T; tc++) {
st = new StringTokenizer(br.readLine());
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
map = new char[R][C];
visited = new boolean[R][C][16][4];
for (int i = 0; i < R; i++) {
String str = br.readLine();
for (int j = 0; j < C; j++) {
map[i][j] = str.charAt(j);
}
}
bfs(tc);
}
}
}
'코딩테스트 > JAVA' 카테고리의 다른 글
[백준 JAVA] 1697번: 숨바꼭질 (0) | 2025.01.06 |
---|---|
[백준 JAVA] 1012번: 유기농 배추 (0) | 2025.01.06 |
[백준 JAVA] 18809번: Gaaaaaaaaaarden (0) | 2024.11.06 |
[프로그래머스 JAVA] 지형 이동 (0) | 2024.10.30 |
[백준 JAVA] 18429번: 근손실 (0) | 2024.10.25 |