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
Solution
球碰壁才停, 使用BFS(的话不能直接visit解决,可能两次到达同一个地方,但是cost不同)所以有可能是(4^N)的空间
from collections import deque
class Solution(object):
def shortestDistance(self, maze, start, destination):
"""
:type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: int
"""
queue = deque([(start,0)])
visited = {(start[0],start[1]):0}
min_v = -1
move = [(0,1),(1,0),(0,-1),(-1,0)]
while len(queue):
cur,dis= queue.popleft()
if cur[0] == destination[0] and cur[1] == destination[1]:
print(min_v,dis)
min_v = dis if min_v ==-1 else min(min_v,dis)
for mov in move:
nextx = cur[0]
nexty = cur[1]
cnt=0
while self.is_valid(nextx,nexty,maze): # hit the wall
nextx+=mov[0]
nexty+=mov[1]
cnt+=1
nextx -=mov[0]
nexty -= mov[1]
cnt-=1
if (nextx,nexty) not in visited:
visited[(nextx,nexty)] = dis+cnt
queue.append(((nextx,nexty),dis+cnt))
else:
cur_dis = visited[(nextx,nexty)]
if cur_dis > dis+cnt:
visited[(nextx,nexty)] = dis+cnt
queue.append(((nextx,nexty),dis+cnt))
return min_v
def is_valid(self,x,y,maze):
width = len(maze[0])
height = len(maze)
if x<0 or x >=height:
return False
if y<0 or y>=width:
return False
if maze[x][y] ==1:
return False
return True
使用DFS较为合适, time O(MNmax(M,N))
public class Solution {
public int shortestDistance(int[][] maze, int[] start, int[] dest) {
int[][] distance = new int[maze.length][maze[0].length];
for (int[] row: distance)
Arrays.fill(row, Integer.MAX_VALUE);
distance[start[0]][start[1]] = 0;
dfs(maze, start, distance);
return distance[dest[0]][dest[1]] == Integer.MAX_VALUE ? -1 : distance[dest[0]][dest[1]];
}
public void dfs(int[][] maze, int[] start, int[][] distance) {
int[][] dirs={{0,1}, {0,-1}, {-1,0}, {1,0}};
for (int[] dir: dirs) {
int x = start[0] + dir[0];
int y = start[1] + dir[1];
int count = 0;
while (x >= 0 && y >= 0 && x < maze.length && y < maze[0].length && maze[x][y] == 0) {
x += dir[0];
y += dir[1];
count++;
}
if (distance[start[0]][start[1]] + count < distance[x - dir[0]][y - dir[1]]) {
distance[x - dir[0]][y - dir[1]] = distance[start[0]][start[1]] + count;
dfs(maze, new int[]{x - dir[0],y - dir[1]}, distance);
}
}
}
}
网友评论