|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Main{ |
| 6 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 8 | + static StringTokenizer st; |
| 9 | + static int N,M; |
| 10 | + static char[][] room; |
| 11 | + static int[] junan = new int[2]; |
| 12 | + static int[] friend = new int[2]; |
| 13 | + static int[] di = {0,0,-1,1}; |
| 14 | + static int[] dj = {-1,1,0,0}; |
| 15 | + public static void main(String[] args) throws Exception { |
| 16 | + st = new StringTokenizer(br.readLine()); |
| 17 | + N = Integer.parseInt(st.nextToken()); |
| 18 | + M = Integer.parseInt(st.nextToken()); |
| 19 | + room = new char[N+1][M+1]; |
| 20 | + |
| 21 | + st = new StringTokenizer(br.readLine()); |
| 22 | + junan[0] = Integer.parseInt(st.nextToken()); |
| 23 | + junan[1] = Integer.parseInt(st.nextToken()); |
| 24 | + friend[0] = Integer.parseInt(st.nextToken()); |
| 25 | + friend[1] = Integer.parseInt(st.nextToken()); |
| 26 | + if(junan[0] == friend[0] && junan[1] == friend[1]){ |
| 27 | + bw.write("0"); |
| 28 | + bw.close(); |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + for (int i = 1; i <= N; i++) { |
| 33 | + String line = br.readLine(); |
| 34 | + for (int j = 1; j <= M; j++) { |
| 35 | + room[i][j] = line.charAt(j-1); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + bw.write(BFS()+""); |
| 40 | + bw.close(); |
| 41 | + } |
| 42 | + static int BFS(){ |
| 43 | + ArrayDeque<int[]> q = new ArrayDeque<>(); |
| 44 | + boolean[][] visited = new boolean[N+1][M+1]; |
| 45 | + q.offer(new int[]{junan[0],junan[1],1}); |
| 46 | + visited[junan[0]][junan[1]] = true; |
| 47 | + |
| 48 | + while(!q.isEmpty()){ |
| 49 | + int[] cur = q.poll(); |
| 50 | + if(cur[0] == friend[0] && cur[1] == friend[1]){ |
| 51 | + return cur[2]; |
| 52 | + } |
| 53 | + for (int k = 0; k < 4; k++) { |
| 54 | + int ni = cur[0] + di[k]; |
| 55 | + int nj = cur[1] + dj[k]; |
| 56 | + |
| 57 | + while (check(ni, nj, visited)){ |
| 58 | + if(room[ni][nj] == '1'){ |
| 59 | + room[ni][nj] = '0'; |
| 60 | + q.offer(new int[]{ni,nj,cur[2]+1}); |
| 61 | + visited[ni][nj] = true; |
| 62 | + break; |
| 63 | + } |
| 64 | + q.push(new int[]{ni,nj,cur[2]}); |
| 65 | + visited[ni][nj] = true; |
| 66 | + ni += di[k]; |
| 67 | + nj += dj[k]; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + return 0; |
| 72 | + } |
| 73 | + static boolean check(int ni,int nj,boolean[][] visited){ |
| 74 | + if(ni<=0 || ni>N || nj<=0 || nj>M || visited[ni][nj]){ |
| 75 | + return false; |
| 76 | + }else{ |
| 77 | + return true; |
| 78 | + } |
| 79 | + } |
| 80 | +} |
| 81 | +``` |
0 commit comments