您的位置:首页 > 其它

Leetcode: Number of Islands

2015-08-25 10:13 260 查看

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

[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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: