国庆中秋长假过完,又要开始上班啦。先刷个题目找找工作状态。
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.
解题思路:本题属于简单级别,但是我还是拿出来分析。因为本题我们可以用广度遍历的算法解决,而广度遍历也是算法中非常重要的一种。步骤如下:
1.从输入的2D数组首元素开始遍历,如果值为0,继续下一个节点;否则,将这个节点入中间过程栈。
2.遍历中间过程栈,将栈中每个节点的上下左右相邻的并且值为1的节点继续入中间过程栈,并计数(这个计数就是表示Area of Island的大小)。注意,每次从栈中取一个新的节点,需要用一个数组记录这个节点是否已经被访问过,保证每个节点只会在中间过程栈中出现一次;同时,对于计数过的节点也要用数组记录,确保每个节点也只能计数一次。
3.如果中间过程栈为空,则继续步骤1,直到2D数组遍历完成。
代码如下:
class Node: def __init__(self,x,y): self.x = x self.y = y class Solution(object): sk = [] def appendNode(self,x,y): for i in self.sk: if i.x == x and i.y == y: return self.sk.append(Node(x,y)) def maxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ visit = [] #record a node if already visisted counted = [] #record a node if already counted width = len(grid[0]) height = len(grid) for i in grid: l = [] for j in i: l.append(0) visit.append(l) counted.append(l) maxCount = 0 for i in range(height): for j in range(width): if visit[i][j] == 1: continue if grid[i][j] == 0: continue n = Node(i,j) self.sk.append(n) count = 1 while len(self.sk) > 0: x = self.sk[0].x y = self.sk[0].y if x+1 < height and visit[x+1][y] == 0 and grid[x+1][y] == 1: if counted[x+1][y] == 0: count += 1 counted[x+1][y] = 1 self.appendNode(x+1,y) if x-1 >= 0 and visit[x-1][y] == 0 and grid[x-1][y] == 1: if counted[x-1][y] == 0: count += 1 counted[x-1][y] = 1 self.appendNode(x-1,y) if y-1 >= 0 and visit[x][y-1] == 0 and grid[x][y-1] == 1: if counted[x][y-1] == 0: count += 1 counted[x][y-1] = 1 self.appendNode(x,y-1) if y+1 <width and visit[x][y+1] == 0 and grid[x][y+1] == 1: if counted[x][y+1] == 0: count += 1 counted[x][y+1] = 1 self.appendNode(x,y+1) visit[x][y] = 1 del self.sk[0] if maxCount < count: maxCount = count return maxCount