Leetcode-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

代码

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)