286. Walls and Gates

Medium


You are given an m x n grid rooms initialized with these three possible values.

  • -1 A wall or an obstacle.
  • 0 A gate.
  • INF Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.

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.

 

Example 1:

Input: rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
Output: [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]

Example 2:

Input: rooms = [[-1]]
Output: [[-1]]

 

Constraints:

  • m == rooms.length
  • n == rooms[i].length
  • 1 <= m, n <= 250
  • rooms[i][j] is -1, 0, or 231 - 1.


SolvingApproachs:

 class Solution:
    def wallsAndGates(self, rooms: List[List[int]]) -> None:
        """
        Do not return anything, modify rooms in-place instead.
        """
        visited = set()
        queue = deque()

        COLS = len(rooms[0])
        ROWS = len(rooms)

        for r in range(ROWS):
            for c in range(COLS):
                if rooms[r][c] == 0:
                    queue.append([r,c])
                    visited.add((r, c))

        def addRoom(r, c):
            if r < 0 or c < 0 or r == ROWS or c == COLS or (r, c) in visited or rooms[r][c] == -1:
                return

            visited.add((r, c))
            queue.append([r,c])

        dist = 0
        while queue:

            for q in range(len(queue)):
                r, c = queue.popleft()
                rooms[r][c] = dist
                addRoom(r+1, c)
                addRoom(r-1, c)
                addRoom(r, c+1)
                addRoom(r, c-1)

            dist+=1

Random Note


Substring a String

  • string[start:end:step]
  • from first string[2:6]
  • last char string[-1]
  • last char by index string[-1]
  • from last string[-5:]
  • first to last string[1:-4]