Formatted question description: https://leetcode.ca/all/505.html

505. The Maze II

Level

Medium

Description

There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it won’t stop rolling until hitting a wall. When the ball stops, it could choose the next direction.

Given the ball’s start position, the destination and the maze, find the shortest distance for the ball to stop at the destination. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included). If the ball cannot stop at the destination, return -1.

The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.

Example 1:

Input 1: a maze represented by a 2D array

0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (4, 4)

Output: 12

Explanation: One shortest way is : left -> down -> left -> down -> right -> down -> right. The total distance is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12.

Image text

Example 2:

Input 1: a maze represented by a 2D array

0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (3, 2)

Output: -1

Explanation: There is no way for the ball to stop at the destination.

Image text

Note:

  1. There is only one ball and one destination in the maze.
  2. Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
  3. The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of the maze are all walls.
  4. The maze contains at least 2 empty spaces, and both the width and height of the maze won’t exceed 100.

Solution

Initialize the distances to INFINITY for all positions except start, which has distance 0. Since the shortest distance is required, use priority queue during the search. Starting from start, each time obtain all possible positions the ball can reach and stop at, update the shortest distances for such positions, and then do further search from the new positions. If the ball can reach and stop at destination, update the shortest distance for destination. After all possible positions are visited, the shortest distances possible are also obtained. If the shortest distance at destination is not INFINITY, return the distance. Otherwise, the ball never reaches and stops at destination, return -1.

class Solution {
    public int shortestDistance(int[][] maze, int[] start, int[] destination) {
        final int WALL = 1;
        int rows = maze.length, columns = maze[0].length;
        int[][] distances = new int[rows][columns];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                if (maze[i][j] == WALL)
                    distances[i][j] = -1;
                else
                    distances[i][j] = Integer.MAX_VALUE;
            }
        }
        int shortestDistance = Integer.MAX_VALUE;
        int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
        distances[start[0]][start[1]] = 0;
        PriorityQueue<PositionDistance> priorityQueue = new PriorityQueue<PositionDistance>();
        priorityQueue.offer(new PositionDistance(start[0], start[1], 0));
        while (!priorityQueue.isEmpty()) {
            PositionDistance positionDistance = priorityQueue.poll();
            int row = positionDistance.getRow(), column = positionDistance.getColumn(), distance = positionDistance.getDistance();
            if (distance > shortestDistance)
                break;
            for (int[] direction : directions) {
                int moveCount = 0;
                int deltaRow = direction[0], deltaColumn = direction[1];
                int stopRow = row, stopColumn = column;
                int curRow = row + deltaRow, curColumn = column + deltaColumn;
                while (curRow >= 0 && curRow < rows && curColumn >= 0 && curColumn < columns && maze[curRow][curColumn] != WALL) {
                    moveCount++;
                    stopRow = curRow;
                    stopColumn = curColumn;
                    curRow += deltaRow;
                    curColumn += deltaColumn;
                }
                int newDistance = distance + moveCount;
                if (newDistance < distances[stopRow][stopColumn]) {
                    distances[stopRow][stopColumn] = newDistance;
                    priorityQueue.offer(new PositionDistance(stopRow, stopColumn, newDistance));
                }
            }
            shortestDistance = Math.min(shortestDistance, distances[destination[0]][destination[1]]);
        }
        if (distances[destination[0]][destination[1]] == Integer.MAX_VALUE)
            return -1;
        else
            return shortestDistance;
    }
}

class PositionDistance implements Comparable<PositionDistance> {
	private int row;
	private int column;
	private int distance;

	public PositionDistance() {
		
	}

	public PositionDistance(int row, int column, int distance) {
		this.row = row;
		this.column = column;
		this.distance = distance;
	}

	public int getRow() {
		return row;
	}

	public int getColumn() {
		return column;
	}

	public int getDistance() {
		return distance;
	}

	public int compareTo(PositionDistance positionDistance2) {
		return this.distance - positionDistance2.distance;
	}
}

All Problems

All Solutions