Saturday, September 2, 2017

LeetCode - 490. The Maze

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

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, determine whether the ball could stop at the destination.
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: for (x,y), we use (start[0], start[1]), so int[] start 
 int[] start, int[] destination
2. Using "BFS" (important)
3. new boolean[][] visited (with the same size as the maze)
boolean[][] visited = new boolean[maze.length][maze[0].length];
4. four directions
int[][] dirs={{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
5.  new a "queue" to process "points", so Queue< int[] >
Queue < int[] > queue = new LinkedList < > ();
6. process the "points" (by using BFS)
while (!queue.isEmpty()) {
}
7. the next point (x,y)
int x = s[0] + dir[0];
int y = s[1] + dir[1];
8. check if the next point (x, y) is valid or not
// note: using "while loop", so it can keep rolling
while (x >= 0 && y >= 0 && x < maze.length && y < maze[0].length && maze[x][y] == 0) {
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 ...