import java.util.*;
import java.lang.*;
import java.io.*;
// The main method must be in a class named "Main".
class Main {
static class Vec2{
int y;
int x;
Vec2(int y, int x) {
this.y = y;
this.x = x;
}
}
static int[] dy = {-1, 0, 1, 0};
static int[] dx = {0, 1, 0, -1};
static final int INF = -1;
static int solveMaze(int h, int w, int[][] maze, int sy, int sx, int gy, int gx) {
Queue<Vec2> q = new ArrayDeque<>();
q.add(new Vec2(sy, sx));
int[][] distance = new int[h][w];
for (int i=0; i<h; i++) {
for (int j=0; j<w; j++) {
distance[i][j] = INF;
}
}
distance[sy][sx] = 0;
while (!q.isEmpty()) {
Vec2 cur = q.poll();
for (int i=0; i<4; i++) {
int ny = cur.y + dy[i];
int nx = cur.x + dx[i];
if (0 <= ny && ny < h && 0<= nx && nx < w) {
if (maze[ny][nx] == 0 && distance[ny][nx] == INF) {
distance[ny][nx] = distance[cur.y][cur.x] + 1;
q.add(new Vec2(ny, nx));
}
}
}
}
return distance[gy][gx];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int h = sc.nextInt(), w = sc.nextInt();
int[][] maze = new int[h][w];
for (int i=0; i<h; i++) {
String line = sc.next();
for (int j=0; j<w; j++) {
maze[i][j] = line.charAt(j) == '#' ? 1 : 0;
}
}
int sy = sc.nextInt() - 1, sx = sc.nextInt() -1;
int gy = sc.nextInt() - 1, gx = sc.nextInt() -1;
int d = solveMaze(h, w, maze, sy, sx, gy, gx);
System.out.println(d);
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: