leetcode 200. Number of Islands DFS

来源:互联网 发布:淘宝托管多少钱一个月 编辑:程序博客网 时间:2024/06/06 01:21

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 __init__(self):        self.dir = [[-1,0],[1,0],[0,-1],[0,1]]    def can(self, x , y):        return  0 <= x < self.n and 0 <= y < self.m and '1' == self.grid[x][y]    def dfs(self, x , y):        self.vis[x][y] = True        for d in self.dir:            nx = x + d[0]            ny = y + d[1]            if self.can(nx , ny) and self.vis[nx][ny] == False:                self.dfs(nx , ny)    def numIslands(self, grid):        self.grid = grid        self.n = len(grid)        if self.n == 0:            return 0        self.m = len(grid[0])        self.vis = [([False]*self.m) for i in range(self.n)]        sum = 0        for i in range(0 , self.n):            for j in range(0 , self.m):                if self.vis[i][j] == False and self.grid[i][j] == '1':                    self.dfs(i , j)                    sum += 1        return sumif __name__ == '__main__':    s = Solution()    print(s.numIslands(['11000','11000','00100','00011']))    print(s.numIslands(['11110', '11010', '11000', '00000']))    print(s.numIslands([[]]))


原创粉丝点击