Saturday, September 2, 2017

LeetCode - 505. The Maze II

Source Link:
https://leetcode.com/articles/the-maze-ii/

Question:
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.

 


My Solution: Note:
1. note: we use int[2] to stand for (x,y), i.e., (int[0], int[1])
int[] start, int[] dest
2.  "new" int[][] to store the distance so far (with the same size as the maze)
int[][] distance = new int[maze.length][maze[0].length];
3. note: need to set the distance as "Integer.MAX_VALUE" (be careful)
for (int[] row: distance)
Arrays.fill(row, Integer.MAX_VALUE);
4. initial setting: the start point
distance[start[0]][start[1]] = 0;
5. note: after while loop, the stop point is "{x - dir[0], y - dir[1]}"
check if the distance is smaller (important)
be careful about the stop point
if (distance[s[0]][s[1]] + count < distance[x - dir[0]][y - dir[1]]) {
// if it is smaller, then update it
distance[x - dir[0]][y - dir[1]] = distance[s[0]][s[1]] + count;
// add the "stop point" into the queue
queue.add(new int[] {x - dir[0], y - dir[1]});
}

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...