Участник:Ковальков Антон М05-903б/Number of Islands

Материал из DISCOPAL
Перейти к: навигация, поиск

https://leetcode.com/problems/number-of-islands/

Python3

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:  
        def get_n(i, j):
            return filter(lambda x: 0 <= x[0] < len(grid) and 0 <= x[1] < len(grid[0]), [(i-1, j), (i+1, j), (i, j+1), (i, j-1)])
 
        count = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '1':
                    count += 1
                    q = [(i, j)]
                    while len(q) != 0:
                        x, y = q.pop()
                        for (m, n) in get_n(x, y):
                            if grid[m][n] == '1':
                                q.append((m, n))
                        grid[x][y] = '0'
        return count