美文网首页
200. Number of Islands

200. Number of Islands

作者: 阿团相信梦想都能实现 | 来源:发表于2016-12-13 16:15 被阅读0次
    class Solution(object):
        def numIslands(self, grid):
            """
            :type grid: List[List[str]]
            :rtype: int
            """
            if not grid: return 0
            m=len(grid)
            n=len(grid[0])
        
            directions=[(0,1),(1,0),(0,-1),(-1,0)]
            def dfs(i,j):
                grid[i][j]='0'
                for direction in directions:
                    x,y=i+direction[0],j+direction[1]
                    if x<0 or x>m-1 or y<0 or y>n-1 or grid[x][y]=='0':
                        continue 
                    dfs(x,y)
                
            count=0
            for i in xrange(m):
                for j in xrange(n):
                    if grid[i][j]=='1':
                        count+=1
                        dfs(i,j)
            return count 
            
    

    相关文章

      网友评论

          本文标题:200. Number of Islands

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