leetcode 200. Number of Islands

200. Number of Islands
题目描述

1 代表岛屿, 0 代表海洋, 1 被 0 包围算作一个岛屿. 只要1被连接, 都只能算一个岛屿.

解题思路

用DFS解题. 遍历grid所有点, 如果grid[i][j]==1, 则对grid[i][j]由四个方向进行DFS, 把所有经过的点标记为x(表示去过), 所以每次遇到grid[i][j]==1的点一定是一个新的岛屿.

代码
Python

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid:
            return 0
        
        def explore(i,j):
            # i was here
            grid[i][j] = 'x' 
            if i > 0 and grid[i - 1][j] == '1':
                explore(i - 1,j)               
            if j > 0 and grid[i][j - 1] == '1':
                explore(i,j - 1)            
            if i < col - 1 and grid[i + 1][j] == '1':
                explore(i + 1,j)     
            if j < row - 1 and grid[i][j + 1] == '1':
                explore(i,j + 1)
        
        noOfIsland = 0      
        col = len(grid)
        row = len(grid[0])
 
        for i in range(col):
            for j in range(row):
                if grid[i][j] == '1':          
                    noOfIsland += 1      
                    # Mark all the points in this island i.e all the points that can be reached from this point
                    explore(i,j)
                
        return noOfIsland
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值