目录
1、题目
给定一个二维的 0-1 矩阵,其中 0 表示海洋,1 表示陆地。单独的或相邻的陆地可以形成岛屿,每个格子只与其上下左右四个格子相邻。求最大的岛屿面积。
Example:
input
vector<vector<int>> grid = {{0,1,1,0},
{0,1,0,0},
{1,1,0,1},
{0,1,0,0}};
output
6
2、思路
先找到为1的陆地,再沿着上下左右的方向找最大的路径,找寻的时候用栈来记录路径,栈的数据结构特点是先进后出,后进先出。走的过程就是侵蚀大陆的过程,最后侵蚀的最大面积就是陆地的最大面积。
3、代码
vector<int> detection={-1, 0, 1, 0, -1};
int maxAreaofIsland(vector<vector<int>> &grid){
int h = grid.size();
int w = h ? grid[0].size() : 0;
int local_area, x, y, area = 0;
for (int i=0; i<h; ++i){
for (int j=0; j<w; ++j){
if (grid[i][j]){
local_area = 1;
grid[i][j] = 0;
stack<pair<int, int>> island;
island.push({i, j});
while (!island.empty()){
auto [ih,iw] = island.top();
island.pop();
for (int k=0; k < 4; ++k){
y = ih+detection[k];
x = iw+detection[k+1];
if (x >= 0 && x < w && y >= 0 && y < h && grid[y][x]==1){
grid[y][x] = 0;
++local_area;
island.push({y, x});
}
}
}
area = max(area, local_area);
}
}
}
return area;
}
4、结果
执行结果:通过
显示详情
添加备注
执行用时:12 ms, 在所有 C++ 提交中击败了95.43%的用户
内存消耗:25.2 MB, 在所有 C++ 提交中击败了23.91%的用户
5、补充
python版代码实现
class Stack(object):
def __init__(self):
self.sa = []
def empty(self):
return len(self.sa) > 0
def pop(self):
top = self.sa.pop(0)
def push(self, element):
self.sa.insert(0, element)
def size(self):
return len(self.sa)
def top(self):
return self.sa[0]
def max_area_of_island(a):
height = len(a)
width = len(a[0])
result = 0
directions = [-1,0,1,0,-1]
for i in range(height):
for j in range(width):
islands = Stack()
if a[i][j] == 1:
tmp = 1
a[i][j] = 0
islands.push((i,j))
while islands.size() > 0:
ci, cj = islands.top()
islands.pop()
for indx in range(len(directions)-1):
xi = directions[indx]
yj = directions[indx+1]
if (height > ci+xi >= 0) and (width > cj+yj >= 0) and (a[ci+xi][cj+yj] == 1):
tmp += 1
a[ci+xi][cj+yj] = 0
islands.push((ci+xi, cj+yj))
if tmp > result:
result = tmp
return result