Code Interview Note
  • 0. Introduction
  • 1. Basic
    • Python Basic
    • Java Basic
    • Primitive Type
    • Basic Question
    • Number
  • 2. Array and Numbers
    • General
    • TwoSum
    • Buy and Sell Stock
    • SubArray
      • SubArray + HashMap
    • Sliding Window
      • Sliding Window At Most Problem
    • Word Break
    • Passes Problem
    • Majority Element
    • Partition Array
    • Sort Colors
    • Anagram
    • Ugly Number
    • TwoPointer
    • Swipe Line
    • Calculator
    • Sudoku
  • 2.1 String
    • String
    • Palindrome
    • Parentheses
    • Decode String
    • Calculator
    • Abbreviation
  • 3. Linkedlist
    • Dummy Node
    • Double Pointers
  • 4. Stack and Queue
    • General
    • Increase/Decrease Stack
  • 5. Binary Search
    • General
    • BS on result
    • Save the half which has result
    • Rotated Sorted Array
    • Split Array Largest Sum
  • 6. Binary Tree
    • General
    • Path Sum
    • Lowest Common Ancestor
    • BST
    • Convert
    • Traverse
    • Valid Ordered Tree
    • Construct Binary Tree
    • Tree depth and width
    • Vertical Order Traverse
  • 7. Heap
    • Geneal
    • TopK
  • 8. Simulation
    • General
    • Read4
    • Encode Decode
    • LRU/LFU
    • Robot
    • GetRandom O(1)
    • Probability
  • 9. DFS
    • Backtrack
    • General
    • Subset
    • Permutation
    • Combination
  • 10. HashTable
    • General
  • 11. Sort
    • General
  • 12. Recursion
    • General
  • 13. Dynamic Programming
    • Graph
    • General
    • Coordinate
    • Double Sequence
    • Longest Common Subsequence
    • Rolling Array
    • House Robber
    • Backpack
    • Memorization
    • Diagonal
  • 14. BFS
    • General
    • Number of Islands
    • The Maze
  • 15. Graph
    • Shortest Path
    • Undirected Graph
    • Topology Sort
    • Word Ladder
    • Tarjan's Algo
  • 16. Divide & Conquer
    • General
  • 17. UnionFind
    • General
    • Grouping
  • 18. Trie
    • General
    • Word Square
  • 19. Company Summary
    • Oracle
    • Amazon
      • DP
    • Google
    • Hackerrank
    • LinkedIn
  • 20. Design
  • 21. Math
  • Behavior Question
  • Internet
  • OS
Powered by GitBook
On this page
  • 490. The Maze
  • 505. The Maze II

Was this helpful?

  1. 14. BFS

The Maze

PreviousNumber of IslandsNext15. Graph

Last updated 4 years ago

Was this helpful?

490. The Maze

Given the ball's start position, the destination and the maze, determine whether the ball could stop at the destination.

"""
利用while loop到達牆壁
只紀錄端點的情況
"""
def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool:
    m, n = len(maze), len(maze[0])
    visited = set(tuple(start))
    q = [start]
    
    while q:
        pos = q.pop(0)
        
        for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            y = pos[0] + dy
            x = pos[1] + dx
            inloop = False
            
            while 0 <= y < m and 0 <= x < n and maze[y][x] == 0:
                inloop = True
                if pos == destination: return True
                y += dy
                x += dx
            
            # 記得退一步
            end = [y-dy, x-dx]
            if inloop and tuple(end) not in visited:
                q.append(end)
                visited.add(tuple(end))
                
    return False

505. The Maze II

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.

def shortestDistance(self, maze: List[List[int]], start: List[int], destination: List[int]) -> int:
    m, n = len(maze), len(maze[0])
    dist = [[float('inf')] * n for _ in range(m)]
    dist[start[0]][start[1]] = 0
    q = [(start[0], start[1], 0)]
    d = destination
    
    while q:
        p1, p2, step = q.pop(0)
        for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            s = step + 1
            y = p1 + dy
            x = p2 + dx
            
            found = False
            inloop = False
            
            while 0 <= y < m and 0 <= x < n and maze[y][x] == 0:
                inloop = True
                if (y, x) == d and s < dist[y][x]:
                    dist[y][x] = [y, x]
                    found = True
                    break       
                s += 1
                y += dy
                x += dx
                
            # 記得退一步
            y, x = y-dy, x-dx
            s -= 1

            if inloop and not found and s < dist[y][x]:
                dist[y][x] = s
                q.append((y, x, s))

    return dist[d[0]][d[1]] if dist[d[0]][d[1]] != float('inf') else -1

499. The Maze III

Given the ball position, the hole position and the maze, find out how the ball could drop into the hole by moving the shortest distance. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the hole (included). Output the moving directions by using 'u', 'd', 'l' and 'r'. Since there could be several different shortest ways, you should output the lexicographically smallest way. If the ball cannot reach the hole, output "impossible".

 def findShortestWay(self, maze: List[List[int]], ball: List[int], hole: List[int]) -> str:
    m, n = len(maze), len(maze[0])
    dist = [[(float('inf'), [])] * n for _ in range(m)]
    q = [(ball[0], ball[1], 0, [''])]
    dirs = {0:'r', 1:'d', 2:'l', 3:'u'}
    
    while q:
        p1, p2, step, routes = q.pop(0)
        for i, (dy, dx) in enumerate(((0, 1), (1, 0), (0, -1), (-1, 0))):
            s = step+1
            y = p1+dy
            x = p2+dx
            new_routes = [r+dirs[i] for r in routes]
            found = False
            inloop = False
            while 0 <= y < m and 0 <= x < n and maze[y][x] == 0:
                inloop = True
                if [y, x] == hole:
                    if s == dist[y][x][0]:
                        dist[y][x] = (s, dist[y][x][1] + new_routes)
                    elif s < dist[y][x][0]:
                        dist[y][x] = (s, new_routes)
                    found = True
                    break
                s += 1
                y += dy
                x += dx
                     
            # 記得退一步
            y, x = y-dy, x-dx
            s -= 1
            if inloop and not found and s <= dist[y][x][0]:
                if s == dist[y][x][0]:
                    dist[y][x] = (s, dist[y][x][1] + new_routes)
                elif s < dist[y][x][0]:
                    dist[y][x] = (s, new_routes)
                q.append((y, x, s, new_routes))

    if dist[hole[0]][hole[1]][0] == float('inf'): return 'impossible'
    return sorted(dist[hole[0]][hole[1]][1])[0]