题解 | #岛屿数量#

岛屿数量

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
全部评论

相关推荐

06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
07-02 10:39
门头沟学院 Java
Steven267:说点真实的,都要秋招了,还没有实习,早干嘛去了,本来学历就差,现在知道急了,而且你这个简历完全可以写成一页,劣势太大了,建议转测试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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