smj007

Untitled

Feb 18th, 2024 (edited)
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. class Solution:
  2.     def islandsAndTreasure(self, grid: List[List[int]]) -> None:
  3.        
  4.         n, m = len(grid), len(grid[0])
  5.         from collections import deque
  6.         q = deque()
  7.         visited = set()
  8.  
  9.         for r in range(n):
  10.             for c in range(m):
  11.                 if grid[r][c] == 0:
  12.                     q.append((r, c))
  13.                     visited.add((r, c))
  14.  
  15.        
  16.         dist = 0
  17.  
  18.         while(q):
  19.             lenq = len(q)
  20.             for i in range(lenq):
  21.                 (row, col) = q.popleft()
  22.  
  23.                 grid[row][col] = dist
  24.                 directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
  25.                 for (dr, dc) in directions:
  26.                     r, c = row+dr, col+dc
  27.  
  28.                     if (r in range(n) and
  29.                         c in range(m) and
  30.                         (r, c) not in visited and
  31.                         grid[r][c]!=-1
  32.                     ):
  33.                         visited.add((r, c))
  34.                         q.append((r, c))
  35.                    
  36.             dist += 1
  37.  
  38. """
  39. Time Complexity:
  40.  
  41. Complexity analysis
  42.  
  43. Time complexity : O(mn)O(mn)O(mn).
  44.  
  45. If you are having difficulty to derive the time complexity, start simple.
  46.  
  47. Let us start with the case with only one gate. The breadth-first search takes at most m×nm \times nm×n steps to reach all rooms, therefore the time complexity is O(mn)O(mn)O(mn). But what if you are doing breadth-first search from kkk gates?
  48.  
  49. Once we set a room's distance, we are basically marking it as visited, which means each room is visited at most once. Therefore, the time complexity does not depend on the number of gates and is O(mn)O(mn)O(mn).
  50.  
  51. Space complexity : O(mn)O(mn)O(mn).
  52. The space complexity depends on the queue's size. We insert at most m×nm \times nm×n points into the queue.
  53.  
  54. """
Add Comment
Please, Sign In to add comment