美文网首页
2019-09-18 ***433. Number of Isl

2019-09-18 ***433. Number of Isl

作者: Mree111 | 来源:发表于2019-10-08 14:47 被阅读0次

Description

Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.

Find the number of islands.

Example
Example 1:

Input:
[
[1,1,0,0,0],
[0,1,0,0,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,0,0,1]
]
Output:
3
Example 2:

Solution

使用bfs可以较好解决,需注意模板格式 queue和visit永远同时更新

from collections import deque
class Solution:
    """
    @param grid: a boolean 2D matrix
    @return: an integer
    """
    def numIslands(self, grid):
        # write your code here
        if not grid or not grid[0]:
            return 0
        visited = set()    
        cnt = 0
        
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid [i][j] and (i,j) not in visited:
                    self.bfs(i,j,grid,visited)
                    cnt +=1
                    
        return cnt  
    def bfs(self,i,j,grid,visited):
        queue=deque([(i,j)])
        visited.add((i,j))
        while queue:
            a,b = queue.popleft()
            for pos in [(0,1),(1,0),(-1,0),(0,-1)]:
                x= a+pos[0]
                y= b+pos[1]
                if not self.is_valid(x,y,grid,visited):
                    continue
                queue.append((x,y))
                visited.add((x,y))
    
    def is_valid(self,x,y,grid,visited):
        n, m = len(grid), len(grid[0])
        if not (0 <= x < n and 0 <= y < m):
            return False
        if (x, y) in visited:
            return False
        return grid[x][y]

相关文章

网友评论

      本文标题:2019-09-18 ***433. Number of Isl

      本文链接:https://www.haomeiwen.com/subject/aszhuctx.html