Advertisement
smj007

Untitled

Aug 14th, 2023
1,067
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  1. class Solution:
  2.     def numIslands(self, grid: List[List[str]]) -> int:
  3.  
  4.         from collections import deque
  5.  
  6.         def bfs(r, c):
  7.  
  8.             q = deque()
  9.             visited.add((r, c))
  10.             q.append((r, c))
  11.  
  12.             while q:
  13.                 row, col = q.popleft()
  14.                 directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
  15.  
  16.                 for dr, dc in directions:
  17.                     r, c = row + dr, col + dc
  18.                     # error was here : r, c = row + dr, row + dc
  19.                     if (r) in range(rows) and (c) in range(cols) and grid[r][c] == '1' and (r ,c) not in visited:
  20.                         q.append((r , c ))
  21.                         visited.add((r, c ))
  22.                
  23.         count = 0
  24.         visited = set()
  25.         rows = len(grid)
  26.         cols = len(grid[0])
  27.  
  28.         for r in range(len(grid)):
  29.             for c in range(len(grid[0])):
  30.                 if grid[r][c] == "1" and (r,c) not in visited:
  31.                     bfs(r, c)
  32.                     count = count + 1
  33.  
  34.         return count
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement