Code
```java
// Time Limit Exceeded
class Solution {
public int shortestDistance(int[][] maze, int[] start, int[] destination) {
if (maze == null || maze.length == 0 || maze[0].length == 0) {
return -1;
}
int rows = maze.length;
int cols = maze[0].length;
int[][] visited = new int[rows][cols];
int[] shortest = new int[1];
shortest[0] = Integer.MAX_VALUE;
shortestDistance(maze, start, destination, visited, 0, shortest);
return shortest[0] == Integer.MAX_VALUE ? -1 : shortest[0];
}
private void shortestDistance(int[][] maze,
int[] start,
int[] destination,
int[][] visited,
int distance,
int[] shortest) {
if (start[0] == destination[0] && start[1] == destination[1]) {
shortest[0] = Math.min(shortest[0], distance);
return;
}
List<int[]> nextLocations = findNextLocations(maze, start, visited);
for (int[] nextLocation : nextLocations) {
if (visited[nextLocation[0]][nextLocation[1]] == 0) {
visited[nextLocation[0]][nextLocation[1]] = 1;
shortestDistance(maze, nextLocation, destination, visited,
distance + calculateDistance(start, nextLocation), shortest);
visited[nextLocation[0]][nextLocation[1]] = 0;
}
}
}
private List<int[]> findNextLocations(int[][] maze, int[] start, int[][] visited) {
List<int[]> nextLocations = new ArrayList<>();
int[] dx = {0, 0, 1, -1};
int[] dy = {1, -1, 0, 0};
for (int i = 0; i < dx.length; i++) {
int[] nextLocation = findNextLocation(maze, start[0], start[1], dx[i], dy[i]);
nextLocations.add(nextLocation);
}
return nextLocations;
}
private int[] findNextLocation(int[][] maze, int x, int y, int dx, int dy) {
int[] nextLocation = new int[]{x, y};
while (isValid(maze, x, y)) {
nextLocation[0] = x;
nextLocation[1] = y;
x += dx;
y += dy;
}
return nextLocation;
}
private boolean isValid(int[][] maze, int x, int y) {
if (0 <= x && x < maze.length && 0 <= y && y < maze[0].length) {
return maze[x][y] == 0;
}
return false;
}
private int calculateDistance(int[] start, int[] end) {
if (start[0] == end[0]) {
return Math.abs(start[1] - end[1]);
}
return Math.abs(start[0] - end[0]);
}
}
```
No comments:
Post a Comment