最大岛屿面积
- 栈+DFS实现
上一篇是直接搜索(DFS),采用递归的思想,本篇是利用栈结构+DFS来实现。
代码实现:(注释很详细)
#include<iostream>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
class Solution {
public:
int direction[5] = { 0,-1,0,1,0 };
int maxAreaOfIsland(vector<vector<int>>& grid) {
const int m = grid.size(), n = grid[0].size();
int area = 0;
stack<int> stack_i;
stack<int> stack_j;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int res = 0;
stack_i.push(i);
stack_j.push(j);
while (!stack_i.empty()) {
int a = stack_i.top(), b = stack_j.top();
stack_i.pop(), stack_j.pop();
for (int index = 0; index < 4; index++) {
int next_i = a + direction[index];
int next_j = b + direction[index+1];
if (next_i<0 || next_j<0 || next_i==m \
|| next_j==n || grid[next_i][next_j] != 1) continue;
res += 1;
grid[next_i][next_j] = 0;
stack_i.push(next_i);
stack_j.push(next_j);
}
}
area = max(area, res);
}
}
return area;
}
};
int main(int argc,char* argv[]){
Solution s;
vector<vector<int>> grid = {
{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,1,0,0,0},
};
cout << s.maxAreaOfIsland(grid) << endl;
return 0;
}