Number of Islands
unknown
plain_text
17 days ago
1.4 kB
2
Indexable
Never
from collections import deque class Solution: def getNeighbors(self,a,b, n, m): neighbors = [] if a > 0: neighbors.append((a-1, b)) if a < n-1: neighbors.append((a+1, b)) if b > 0: neighbors.append((a, b-1)) if b < m-1: neighbors.append((a, b+1)) return neighbors def numIslands(self, grid): queue = deque() visited = set() hight = len(grid) width = len(grid[0]) ans = 0 for i in range(hight): for j in range(width): if (i,j) not in visited and grid[i][j] != '0': queue.append((i, j)) while queue: size = len(queue) for _ in range(size): cur = queue.popleft() (a, b) = cur neighbors = self.getNeighbors(a,b, hight, width) for neighbor in neighbors: (a, b) = neighbor if neighbor not in visited and grid[a][b] != '0': queue.append(neighbor) visited.add(neighbor) ans += 1 return ans grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["0","1","1","0","0"], ["1","0","1","0","1"] ] solution = Solution() result = solution.numIslands(grid) print(result) # طباعة عدد الجزر # print(getNeighbors(1,1, 4, 5))
Leave a Comment