题解 | #岛屿数量#

岛屿数量

http://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e

DFS: once '1' is found then trigger dfs() to search all adjacent '1' and flip them as '0', since all adjacent '1' are regarded as one island. Use for loop to go through the grid.
Big O time complexity as O(rc) r- number of rows, c-number of columns.
BIg O space complexity as:O(r
c). since in the worst case, the whole grid are filled with '1' then the dfs searching depth would be area of grid: r*c

class Solution:
    def solve(self , grid ):

        # write code heren 
        nr=len(grid)
        nc=len(grid[0])
        nums=0
        def dfs(grid,r,c):
            grid[r][c]=0
            # flip adjacent 1 to be zero since they are connected and regarded as one island
            for (x,y) in [(r-1,c),(r+1,c),(r,c-1),(r,c+1)]:
                if 0<=x<nr and 0<=y<nc and grid[x][y]=='1':
                    dfs(grid,x,y)

        for i in range(nr):
            for j in range(nc):
                if grid[i][j]=='1':
                    nums+=1
                    dfs(grid,i,j)
        return nums
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 11:30
找工作7个月,投了7000封,3段世界五百强实习,才有一个offer,牛油们肯定比我强吧
码农索隆:不对不对不对,实习经历这么厉害,简历也没少投,问题出在哪呢
点赞 评论 收藏
分享
06-12 16:23
已编辑
小米_软件开发(准入职员工)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务