Leetcode: Number of Islands

来源:互联网 发布:剑三捏脸数据成男 编辑:程序博客网 时间:2024/05/10 18:08

Question

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Show Tags
Show Similar Problems


Solution

Analysis

refer to GeeksforGeeks.

“Quotation
This is an variation of the standard problem: “Counting number of connected components in a undirected graph”

The code is from 西施豆腐渣.

Code

class Solution(object):    def numIslands(self, grid):        """        :type grid: List[List[str]]        :rtype: int        """        if grid==[]:            return 0        row, col = len(grid), len(grid[0])        count = 0        for r in range(row):            for c in range(col):                if grid[r][c]=='1':                    self.search(grid, r, c)                    count += 1        return count    def search(self, grid, r, c):        if r<0 or r>=len(grid) or c<0 or c>=len(grid[0]) or grid[r][c]=='0':            return        grid[r][c] = '0'        self.search(grid, r-1, c)        self.search(grid, r+1, c)        self.search(grid, r, c+1)        self.search(grid, r, c-1)
0 0
原创粉丝点击