代码改变世界

[LeetCode] 200. Number of Islands_ Medium tag: BFS

2018-07-04 04:40  Johnson_强生仔仔  阅读(369)  评论(0编辑  收藏  举报

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:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

这个题目也是经典的BFS, 思路就是将2D array扫一遍, 然后每次如果扫到的元素是'1' and not in visited, ans += 1, 并且建一个queue, 将所有跟它相邻的4个元素如果是'1' 并且没有visited过的,
append进入queue, mark 为visited, recursively直到把所有4个方向的'1' 的元素都mark为visited, 然后一直把整个array扫完, 然后return ans.



1. Constraints

1) array can be empty or col == 0 , return 0
2) the element in array will only be '1' or '0'


2. Ideas

BFS: T: O(m*n) S: O(m*n)


3. Code

 1 class Solution:
 2     def numIslands(self, grid):
 3         ans,visited = 0, set()
 4         if not grid or len(grid[0]) == 0: return ans
 5         lr, lc = len(grid), len(grid[0])
 6         for i in range(lr):
 7             for j in range(lc):
 8                 if grid[i][j] == '1' and (i,j) not in visited:
 9                     ans += 1
10                     visited.add((i,j))
11                     queue, dirs = collections.deque([(i,j)]), [(0,1), (0,-1), (-1,0), (1,0)]
12                     while queue:
13                         r, c = queue.popleft()
14                         for d1, d2 in dirs:
15                             nr, nc = r + d1, c + d2
16                             if 0<= nr < lr and 0<= nc < lc and grid[nr][nc] == '1' and (nr, nc) not in visited:
17                                 queue.append((nr, nc))
18                                 visited.add((nr,nc))
19         return ans

 

4. test cases

1) [], [[]]

2) [[1]]

3) 

Input:
11110
11010
11000
00000

Output: 1

4)

Input:
11000
11000
00100
00011

Output: 3