|
| 1 | +```java |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | +import java.io.*; |
| 5 | + |
| 6 | + |
| 7 | +class Main { |
| 8 | + |
| 9 | + // IO field |
| 10 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 11 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 12 | + static StringTokenizer st; |
| 13 | + |
| 14 | + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} |
| 15 | + static int nextInt() {return Integer.parseInt(st.nextToken());} |
| 16 | + static long nextLong() {return Long.parseLong(st.nextToken());} |
| 17 | + static void bwEnd() throws Exception {bw.flush();bw.close();} |
| 18 | + |
| 19 | + // Additional field |
| 20 | + static int[] dx = {1,0,-1,0}; |
| 21 | + static int[] dy = {0,1,0,-1}; |
| 22 | + |
| 23 | + static char[][] arr; |
| 24 | + static boolean[][][] vis; |
| 25 | + static int N, M; |
| 26 | + |
| 27 | + public static void main(String[] args) throws Exception { |
| 28 | + |
| 29 | + ready(); |
| 30 | + solve(); |
| 31 | + |
| 32 | + bwEnd(); |
| 33 | + } |
| 34 | + |
| 35 | + static void ready() throws Exception{ |
| 36 | + nextLine(); |
| 37 | + N = nextInt(); |
| 38 | + M = nextInt(); |
| 39 | + arr = new char[N][M]; |
| 40 | + vis = new boolean[N][M][2]; |
| 41 | + for(int i=0;i<N;i++) arr[i] = br.readLine().toCharArray(); |
| 42 | + |
| 43 | + } |
| 44 | + |
| 45 | + static void solve() throws Exception{ |
| 46 | + |
| 47 | + for(int i=0;i<N;i++) for(int j=0;j<M;j++) if(arr[i][j] == 'S') { |
| 48 | + bw.write(bfs(i,j)+"\n"); |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + } |
| 53 | + |
| 54 | + static int bfs(int sx, int sy) throws Exception { |
| 55 | + |
| 56 | + Queue<int[]> Q = new LinkedList<>(); |
| 57 | + vis[sx][sy][0] = true; |
| 58 | + Q.offer(new int[] {sx,sy,0,0}); |
| 59 | + |
| 60 | + while(!Q.isEmpty()) { |
| 61 | + int[] now = Q.poll(); |
| 62 | + int x = now[0], y = now[1], v = now[2], t = now[3]; |
| 63 | + if(arr[x][y] == 'H' && v == 1) return t; |
| 64 | + |
| 65 | + for(int i=0;i<4;i++) { |
| 66 | + int xx = x+dx[i], yy = y+dy[i]; |
| 67 | + if(xx<0 || xx>=N || yy<0 || yy>=M || arr[xx][yy] == 'D') continue; |
| 68 | + int vv = arr[xx][yy] == 'F' ? 1 : v; |
| 69 | + if(vis[xx][yy][vv]) continue; |
| 70 | + Q.offer(new int[] {xx,yy,vv,t+1}); |
| 71 | + vis[xx][yy][vv] = true; |
| 72 | + } |
| 73 | + } |
| 74 | + return -1; |
| 75 | + |
| 76 | + } |
| 77 | + |
| 78 | +} |
| 79 | + |
| 80 | +``` |
0 commit comments