|
| 1 | +# Time: O(m * n) |
| 2 | +# Space: O(m + n) |
| 3 | + |
| 4 | +# bi-bfs solution |
| 5 | +class Solution(object): |
| 6 | + def nearestExit(self, maze, entrance): |
| 7 | + """ |
| 8 | + :type maze: List[List[str]] |
| 9 | + :type entrance: List[int] |
| 10 | + :rtype: int |
| 11 | + """ |
| 12 | + directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] |
| 13 | + visited = ' ' |
| 14 | + entrance = tuple(entrance) |
| 15 | + left = set([entrance]) |
| 16 | + right = set([(r, 0) for r in xrange(len(maze)-1) if maze[r][0] == '.' and (r, 0) != entrance] + |
| 17 | + [(len(maze)-1, c) for c in xrange(len(maze[0])-1) if maze[len(maze)-1][c] == '.' and (len(maze)-1, c) != entrance] + |
| 18 | + [(r, len(maze[0])-1) for r in reversed(xrange(1, len(maze))) if maze[r][len(maze[0])-1] == '.' and (r, len(maze[0])-1) != entrance] + |
| 19 | + [(0, c) for c in reversed(xrange(1, len(maze[0]))) if maze[0][c] == '.' and (0, c) != entrance]) |
| 20 | + steps = 0 |
| 21 | + while left: |
| 22 | + for (r, c) in left: |
| 23 | + maze[r][c] = visited |
| 24 | + new_left = set() |
| 25 | + for (r, c) in left: |
| 26 | + if (r, c) in right: |
| 27 | + return steps |
| 28 | + for dr, dc in directions: |
| 29 | + nr, nc = r+dr, c+dc |
| 30 | + if not (0 <= nr < len(maze) and |
| 31 | + 0 <= nc < len(maze[0]) and |
| 32 | + maze[nr][nc] == '.'): |
| 33 | + continue |
| 34 | + new_left.add((nr, nc)) |
| 35 | + left = new_left |
| 36 | + steps += 1 |
| 37 | + if len(left) > len(right): |
| 38 | + left, right = right, left |
| 39 | + return -1 |
| 40 | + |
| 41 | + |
| 42 | +# Time: O(m * n) |
| 43 | +# Space: O(m + n) |
| 44 | +# bfs solution |
| 45 | +class Solution2(object): |
| 46 | + def nearestExit(self, maze, entrance): |
| 47 | + """ |
| 48 | + :type maze: List[List[str]] |
| 49 | + :type entrance: List[int] |
| 50 | + :rtype: int |
| 51 | + """ |
| 52 | + directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] |
| 53 | + visited = ' ' |
| 54 | + entrance = tuple(entrance) |
| 55 | + maze[entrance[0]][entrance[1]] = visited |
| 56 | + q = [(entrance, 0)] |
| 57 | + while q: |
| 58 | + new_q = [] |
| 59 | + for (r, c), step in q: |
| 60 | + if (r, c) != entrance and \ |
| 61 | + (r in (0, len(maze)-1) or c in (0, len(maze[0])-1)): |
| 62 | + return step |
| 63 | + for dr, dc in directions: |
| 64 | + nr, nc = r+dr, c+dc |
| 65 | + if not (0 <= nr < len(maze) and |
| 66 | + 0 <= nc < len(maze[0]) and |
| 67 | + maze[nr][nc] == '.'): |
| 68 | + continue |
| 69 | + maze[nr][nc] = visited |
| 70 | + q.append(((nr, nc), step+1)) |
| 71 | + q = new_q |
| 72 | + return -1 |
0 commit comments