题目
思路
回溯法
盲区
1 vector<vector<int>> 二维vector的初始化、使用、优点
2 深度优先遍历
3 树的最大深度、最小深度、平衡树(“从上到下传递,从下至上解决”需要单写一篇文章)
代码
之前运行时候的内存泄漏问题,是因为动态数组entered[]越界,因为我在遍历二维矩阵的时候采用了row*rows+col,然而矩阵不一定是方阵。粗心了,之前没有检查到。
排除了这个错误,大部分案例都能通过了。因为是采用的回溯法,在遇到大型矩阵的时候会出现内存错误。这个就要通过采用循环/动态规划优化代码了。因为时间问题,这里先不讨论。有兴趣可以学习一下网上其他解答。
#include <iostream>
#include <vector>
using namespace std;
int traverse(vector<vector<int> >& inputGrid, bool* entered, int rows, int cols, int row, int col);
int maxAreaOfIsland(vector<vector<int> >& grid)
{
if (!grid.size())
return 0;
int rows = grid.size();
int cols = grid[0].size();
bool* entered = new bool[rows*cols];
for (int i = 0; i < rows*cols; i++)
{
entered[i] = false;
}
int max = 0;
int tmp = 0;
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
tmp = traverse(grid, entered, rows, cols, i, j);
if (tmp>max)
max = tmp;
}
}
delete[]entered;
return max;
}
int traverse(vector<vector<int>>& inputGrid, bool* entered, int rows, int cols, int row, int col)
{
if (row<0 || col<0 || row>=rows || col>=cols)
return 0;
if (entered[row*cols + col])
{
return 0;
}
if (inputGrid[row][col] == 0)
{
//entered[row*cols + col] = true;
return 0;
}
entered[row*cols + col] = true;
int tmp = 1 + traverse(inputGrid, entered, rows, cols, row, col - 1) +
traverse(inputGrid, entered, rows, cols, row, col + 1) +
traverse(inputGrid, entered, rows, cols, row - 1, col) +
traverse(inputGrid, entered, rows, cols, row + 1, col);
return tmp;
}
复制代码
参考文献
[2] Max area of island (Array)