代码改变世界

[LeetCode] 695. Max Area of Island_Medium tag: DFS/BFS

2019-11-24 00:07  Johnson_强生仔仔  阅读(228)  评论(0编辑  收藏  举报

Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 1:

[[0,0,1,0,0,0,0,1,0,0,0,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,1,1,0,1,0,0,0,0,0,0,0,0],
 [0,1,0,0,1,1,0,0,1,0,1,0,0],
 [0,1,0,0,1,1,0,0,1,1,1,0,0],
 [0,0,0,0,0,0,0,0,0,0,1,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,0,0,0,0,0,0,1,1,0,0,0,0]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

Example 2:

[[0,0,0,0,0,0,0,0]]

Given the above grid, return 0.

Note: The length of each dimension in the given grid does not exceed 50.

 

这个题目就是基本的BFS,两个for loop去扫2D array, 每个grid[i][j]如果是1 并且没有被visited过的,那么就去bfs一遍,得到的size来与ans比较,最后返回ans。

T: O(m * n)

 

Code

class Solution(object):
    def maxAreaOfIsland(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        lr, lc, dirs, visited, ans, queue = len(grid), len(grid[0]), [(1, 0), (-1, 0), (0, -1), (0, 1)], set(), 0, collections.deque()
        for i in range(lr):
            for j in range(lc):
                if grid[i][j] == 1 and (i, j) not in visited:
                    size = 0
                    queue.append((i, j))
                    visited.add((i, j))
                    while queue:
                        r, c = queue.popleft()
                        size += 1
                        for d1, d2 in dirs:
                            nr, nc = r + d1, c + d2
                            if 0 <= nr < lr and 0 <= nc < lc and (nr, nc) not in visited and grid[nr][nc] == 1:
                                queue.append((nr, nc))
                                visited.add((nr, nc))
                    ans = max(ans, size)
        return ans