200.岛屿数量

from collections import deque
class Solution:
    def numIslands(self, grid) -> int:
        m=len(grid)
        if not m:
            return 0
        n=len(grid[0])
        count=0
        for i in range(m):
            for j in range(n):
                if grid[i][j]=='1':
                    queue=deque()
                    queue.append((i,j))
                    while queue:
                        x=queue.pop()
                        iii,jjj=x[0],x[1]
                        grid[iii][jjj]='0'
                        for ii,jj in [[-1,0],[1,0],[0,1],[0,-1]]:
                            x,y=iii+ii,jjj+jj
                            if 0<=x<m and 0<=y<n and grid[x][y]=='1':
                                queue.append((x,y))
                    count+=1
        return count
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        def func(i,j):
            grid[i][j]='0'
            if i-1>-1 and grid[i-1][j]=='1':
                func(i-1,j)
            if i+1<m and grid[i+1][j]=='1':
                func(i+1,j)
            if j-1>-1 and grid[i][j-1]=='1':
                func(i,j-1)
            if j+1<n and grid[i][j+1]=='1':
                func(i,j+1)
        m=len(grid)
        if not m:
            return 0
        n=len(grid[0])
        count=0
        for i in range(m):
            for j in range(n):
                if grid[i][j]=='1':
                    func(i,j)
                    count+=1
        return count
from collections import deque
class Solution:
    def numIslands(self, grid) -> int:
        m=len(grid)
        if not m:
            return 0
        n=len(grid[0])
        count=0
        for i in range(m):
            for j in range(n):
                if grid[i][j]=='1':
                    queue=deque()
                    queue.append((i,j))
                    grid[i][j]='0'
                    count+=1
                    while queue:
                        cur=queue.popleft()
                        for ii,jj in [[-1,0],[1,0],[0,1],[0,-1]]:
                            x,y=cur[0]+ii,cur[1]+jj
                            if 0<=x<m and 0<=y<n and grid[x][y]=='1':
                                grid[x][y]='0'
                                queue.append((x,y))
        return count
posted @ 2019-08-17 00:35  NeoZy  阅读(124)  评论(0编辑  收藏  举报