Advertisement
miglss

31.YA

Apr 13th, 2025
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. def solution(grid: list) -> int:
  2.     rows = len(grid)
  3.     cols = len(grid[0])
  4.     ans = 0
  5.     seen = set()
  6.    
  7.     def validate(x, y):
  8.         if x >= 0 and x < rows:
  9.             if y >= 0 and y < cols:
  10.                 return True
  11.         return False
  12.    
  13.     def dfs(row, col):
  14.         stack = [(row, col)]
  15.         while stack:
  16.             x, y = stack.pop()
  17.            
  18.             for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
  19.                 if validate(x+dx, y+dy):
  20.                     if grid[x+dx][y+dy] == '1' and (x+dx, y+dy) not in seen:
  21.                         seen.add((x+dx, y+dy))
  22.                         stack.append((x+dx, y+dy))
  23.    
  24.     for row in range(rows):
  25.         for col in range(cols):
  26.             # Нашли остров, который не посещали ранее
  27.             if grid[row][col] == '1' and (row, col) not in seen:
  28.                 ans += 1
  29.                 seen.add((row, col))
  30.                 dfs(row, col)
  31.    
  32.     return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement