美文网首页
Leetcode-200题:Number of Islands

Leetcode-200题:Number of Islands

作者: 八刀一闪 | 来源:发表于2016-09-26 22:01 被阅读44次

题目

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

代码

class Solution(object):

    def depth_search(self, grid, visit, i, j):
        stack = [(i,j)]
        while len(stack) != 0:
            (m,n) = stack.pop()
            visit[m][n] = True
            if m!=0 and grid[m-1][n]=='1' and visit[m-1][n]==False:
                stack.append((m-1,n))
            if n!=0 and grid[m][n-1]=='1' and visit[m][n-1]==False:
                stack.append((m,n-1))
            if m!=len(grid)-1 and grid[m+1][n]=='1' and visit[m+1][n]==False:
                stack.append((m+1,n))
            if n!=len(grid[0])-1 and grid[m][n+1]=='1' and visit[m][n+1]==False:
                stack.append((m,n+1))

    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        if grid==None or len(grid)==0:
            return 0
        counter = 0
        visit = [[False] * len(grid[0]) for i in range(len(grid))]
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j]=='0' or visit[i][j]:
                    continue
                counter += 1
                self.depth_search(grid, visit, i, j)
        return counter

相关文章

网友评论

      本文标题:Leetcode-200题:Number of Islands

      本文链接:https://www.haomeiwen.com/subject/ctaqyttx.html