题解 | #岛屿数量#

岛屿数量

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

相关推荐

01-11 02:09
已编辑
华中师范大学 golang
京京洪洪学java:如果坚定转Java就要先做好暑期结果可能没那么好的准备,大厂也有做go的,也有接受内部切换技术栈的,go怎么就不行了呢?,ACM+华师肯定能接到一些大厂面试的,acm铜的基础可以让你比较轻松地应对中大厂的手撕,就是八股和项目要下硬功夫,至于找不到go项目?github上一直刷啊,跟刷b站主页一样,那么多好的go开源项目,怎么会找不到呢?刷到想学感兴趣的用ai吃透,试着改进或者吸收作为自己的项目,另一个选择就是考研了。
点赞 评论 收藏
分享
搞机墨镜猫:科研和竞赛全写成项目经历,另外你项目涉及到的技术栈太杂了,应该对不同岗位强调写不同的技术栈,寒假应该不太好找短期,长期明年3,4月好找很多
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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