Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.StringTokenizer;
- public class Main {
- static int N, M;
- static char[][] arr;
- static int ret; // 결과값
- static int[] dy = { 0, 1, -1 }, dx = { 1, 1, 1 };
- static boolean flag = false; // 당근이 없고 쪽문으로 도착했을경우, 결과값이 0일 수 있기 때문에 플래그 변수 생성
- static void dfs(int y, int x, int cnt, char c) {
- if (c == 'O') {
- flag = true; // 쪽문으로 빠져나왔다면 플래그 true로 변경
- ret = Math.max(ret, cnt); // 최대값이라면 최신화
- return;
- }
- for (int i = 0; i < 3; i++) {
- int gy = y + dy[i];
- int gx = x + dx[i];
- if (0 <= gy && gy < N && gx < M) {
- if (arr[gy][gx] == '#')
- continue;
- if (arr[gy][gx] == 'C') {
- dfs(gy, gx, cnt + 1, 'C');
- } else { // '.' or 'O'
- dfs(gy, gx, cnt, arr[gy][gx]);
- }
- }
- }
- }
- public static void main(String[] args) throws IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- StringTokenizer st = new StringTokenizer(br.readLine());
- N = Integer.parseInt(st.nextToken());
- M = Integer.parseInt(st.nextToken());
- arr = new char[N][M];
- int sy = 0, sx = 0;
- for (int i = 0; i < N; i++) {
- String input = br.readLine();
- for (int j = 0; j < M; j++) {
- char ch = input.charAt(j);
- if (ch == 'R') { // '토끼의 처음위치(y,x) 저장
- sy = i;
- sx = j;
- }
- arr[i][j] = ch;
- }
- }
- dfs(sy, sx, 0, 'R');
- if (!flag) // 한번도 쪽문에 가지 못했다 == 도착하지 못했다 : -1 출력
- System.out.println(-1);
- else
- System.out.println(ret);
- br.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment