Guest User

kkk

a guest
Apr 10th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.StringTokenizer;
  5.  
  6. public class Main {
  7.  
  8.     static int N, M;
  9.     static char[][] arr;
  10.     static int ret; // 결과값
  11.     static int[] dy = { 0, 1, -1 }, dx = { 1, 1, 1 };
  12.     static boolean flag = false; // 당근이 없고 쪽문으로 도착했을경우, 결과값이 0일 수 있기 때문에 플래그 변수 생성
  13.  
  14.     static void dfs(int y, int x, int cnt, char c) {
  15.         if (c == 'O') {
  16.             flag = true; // 쪽문으로 빠져나왔다면 플래그 true로 변경
  17.             ret = Math.max(ret, cnt); // 최대값이라면 최신화
  18.             return;
  19.         }
  20.  
  21.         for (int i = 0; i < 3; i++) {
  22.             int gy = y + dy[i];
  23.             int gx = x + dx[i];
  24.             if (0 <= gy && gy < N && gx < M) {
  25.                 if (arr[gy][gx] == '#')
  26.                     continue;
  27.                 if (arr[gy][gx] == 'C') {
  28.                     dfs(gy, gx, cnt + 1, 'C');
  29.                 } else { // '.' or 'O'
  30.                     dfs(gy, gx, cnt, arr[gy][gx]);
  31.                 }
  32.             }
  33.         }
  34.     }
  35.  
  36.     public static void main(String[] args) throws IOException {
  37.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  38.         StringTokenizer st = new StringTokenizer(br.readLine());
  39.         N = Integer.parseInt(st.nextToken());
  40.         M = Integer.parseInt(st.nextToken());
  41.         arr = new char[N][M];
  42.  
  43.         int sy = 0, sx = 0;
  44.         for (int i = 0; i < N; i++) {
  45.             String input = br.readLine();
  46.             for (int j = 0; j < M; j++) {
  47.                 char ch = input.charAt(j);
  48.                 if (ch == 'R') { // '토끼의 처음위치(y,x) 저장
  49.                     sy = i;
  50.                     sx = j;
  51.                 }
  52.                 arr[i][j] = ch;
  53.             }
  54.         }
  55.        
  56.         dfs(sy, sx, 0, 'R');
  57.        
  58.         if (!flag) // 한번도 쪽문에 가지 못했다 == 도착하지 못했다 : -1 출력
  59.             System.out.println(-1);
  60.         else
  61.             System.out.println(ret);
  62.  
  63.         br.close();
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment