Guest User

kkk1

a guest
Apr 10th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.LinkedList;
  5. import java.util.Queue;
  6. import java.util.StringTokenizer;
  7.  
  8. public class Main {
  9.  
  10.     static int N, M;
  11.     static char[][] arr;
  12.     static int[] dy = { 0, 1, -1 }, dx = { 1, 1, 1 };
  13.  
  14.     public static void main(String[] args) throws IOException {
  15.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  16.         StringTokenizer st = new StringTokenizer(br.readLine());
  17.         N = Integer.parseInt(st.nextToken());
  18.         M = Integer.parseInt(st.nextToken());
  19.         arr = new char[N][M];
  20.  
  21.         int sy = 0, sx = 0;
  22.         for (int i = 0; i < N; i++) {
  23.             String input = br.readLine();
  24.             for (int j = 0; j < M; j++) {
  25.                 char ch = input.charAt(j);
  26.                 if (ch == 'R') { // '토끼의 처음위치(y,x) 저장
  27.                     sy = i;
  28.                     sx = j;
  29.                 }
  30.                 arr[i][j] = ch;
  31.             }
  32.         }
  33.  
  34.         Queue<Loc> q = new LinkedList<Loc>();
  35.         q.offer(new Loc(sy, sx, 0));
  36.         int ret = -1;
  37.  
  38.         while (!q.isEmpty()) {
  39.             Loc r = q.poll();
  40.  
  41.             for (int i = 0; i < 3; i++) {
  42.                 int gy = r.y + dy[i];
  43.                 int gx = r.x + dx[i];
  44.                 if (0 <= gy && gy < N && gx < M) {
  45.                     if (arr[gy][gx] == '#')
  46.                         continue;
  47.                     if (arr[gy][gx] == 'C') {
  48.                         q.add(new Loc(gy, gx, r.c + 1));
  49.                     } else if (arr[gy][gx] == '.') {
  50.                         q.add(new Loc(gy, gx, r.c));
  51.                     } else if (arr[gy][gx] == 'O') {
  52.                         ret = Math.max(ret, r.c);
  53.                     }
  54.                 }
  55.             }
  56.         }
  57.         System.out.println(ret);
  58.  
  59.         br.close();
  60.     }
  61.  
  62.     static class Loc {
  63.         int y, x, c;
  64.  
  65.         Loc(int y, int x, int c) {
  66.             this.y = y;
  67.             this.x = x;
  68.             this.c = c;
  69.         }
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment