LeetCode No.200 Number of Islands

题目

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

题意

给定一个由0,1组成的矩阵,1表示陆地,一个岛是由横竖相邻的1组成的。计算矩阵中岛屿的个数。

解题思路

遍历矩阵,对于每一个点(x,y)递归的查找(x + 1,y),(x - 1,y),(x,y + 1),(x,y - 1)是否为陆地。

代码

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        count = 0
        col = len(grid)
        if col == 0:
            return count
        row = len(grid[0])
        for i in range(col):
            for j in range(row):
                if (grid[i][j] == '1'):
                    self.search(grid,i,j)
                    count += 1
        return count

    def search(self, grid, x, y):
        """
        :type grid:List[List[str]]
        :param grid:
        :param x:
        :param y:
        """
        col = len(grid)
        row = len(grid[0])
        if x < 0 or x >= col or y < 0 or y >= row or grid[x][y] != '1':
            return
        grid[x][y] = '0'
        self.search(grid,x + 1,y)
        self.search(grid,x - 1,y)
        self.search(grid,x,y + 1)
        self.search(grid,x,y - 1)

相关链接

源代码(github)
原题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值