class Solution { public int shortestDistance(int[][] maze, int[] start, int[] destination) { int nr = maze.length; int nc = maze[0].length; int[][] distances = new int[nr][nc]; for (int[] row : distances) { Arrays.fill(row, Integer.MAX_VALUE); } int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; Queue queue = new LinkedList<>(); queue.add(start); while (!queue.isEmpty()) { int[] curr = queue.poll(); for (int[] dir : dirs) { int x = curr[0] + dir[0]; int y = curr[1] + dir[1]; int count = 0; while (x >= 0 && x < nr && y >= 0 && y < nc && maze[x][y] != 1) { x += dir[0]; y += dir[1]; count++; } if (distances[curr[0]][curr[1]] + count < distances[x-dir[0]][y-dir[1]]) { distances[x-dir[0]][y-dir[1]] = distances[curr[0]][curr[1]] + count; queue.add(new int[]{x - dir[0], y - dir[1]}); } } } return distances[destination[0]][destination[1]] == Integer.MAX_VALUE ? -1 : distances[destination[0]][destination[1]]; } }