General

286. Walls and Gates

you are given a m x n 2D grid initialized with these three possible values.

-1 is a wall, 0 is a gate. INF is empty.

Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.

  • 用queue儲存gates, 從gate出發, if empty, +1 distance

def wallsAndGates(self, rooms: List[List[int]]) -> None:
    """
    Do not return anything, modify rooms in-place instead.
    """
    if not rooms: return
    m, n = len(rooms), len(rooms[0])
    q = []
    
    for i in range(m):
        for j in range(n):
            if rooms[i][j] == 0:
                q.append((i, j))
    
    step = 0
    while q:
        step += 1
        size = len(q)
        while size > 0:
            i, j = q.pop(0)
            for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)):
                y, x = i + dy, j+ dx
                if not (0 <= y < m and 0 <= x < n): continue
                if rooms[y][x] == 2147483647:
                    rooms[y][x] = step
                    q.append((y, x))
            size-=1

317. Shortest Distance from All Buildings

You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:

  • Each 0 marks an empty land which you can pass by freely.

  • Each 1 marks a building which you cannot pass through.

  • Each 2 marks an obstacle which you cannot pass through.

909. Snakes and Ladders

  1. 牛耕式轉行法,注意行列變換

  2. BFS

  3. A visit set 避免loop

Last updated

Was this helpful?