class Solution {
public:
void numIslands2(vector<vector<char>>& grid, int i, int j, int & nn, vector<vector<char>> & find) {
int m = grid.size();
int n = grid[0].size();
if (i >= 0 && i < m && j >= 0 && j < n && grid[i][j] == '1' && find[i][j] == 0)
{
find[i][j] = nn;
numIslands2(grid, i + 1, j, nn, find);
numIslands2(grid, i, j + 1, nn, find);
numIslands2(grid, i - 1, j, nn, find);
numIslands2(grid, i, j - 1, nn, find);
}
}
int numIslands(vector<vector<char>>& grid) {
if (grid.empty())
return 0;
int m = grid.size();
int n = grid[0].size();
vector<vector<char>> find;
for (int i = 0; i < m; i++)
{
vector<char> tmp;
for (int j = 0; j < n; j++)
{
tmp.push_back(0);
}
find.push_back(tmp);
}
int nn = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (grid[i][j] == '1' && find[i][j] == 0)
{
nn++;
numIslands2(grid, i, j, nn, find);
}
}
}
return nn;
}
};
public:
void numIslands2(vector<vector<char>>& grid, int i, int j, int & nn, vector<vector<char>> & find) {
int m = grid.size();
int n = grid[0].size();
if (i >= 0 && i < m && j >= 0 && j < n && grid[i][j] == '1' && find[i][j] == 0)
{
find[i][j] = nn;
numIslands2(grid, i + 1, j, nn, find);
numIslands2(grid, i, j + 1, nn, find);
numIslands2(grid, i - 1, j, nn, find);
numIslands2(grid, i, j - 1, nn, find);
}
}
int numIslands(vector<vector<char>>& grid) {
if (grid.empty())
return 0;
int m = grid.size();
int n = grid[0].size();
vector<vector<char>> find;
for (int i = 0; i < m; i++)
{
vector<char> tmp;
for (int j = 0; j < n; j++)
{
tmp.push_back(0);
}
find.push_back(tmp);
}
int nn = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (grid[i][j] == '1' && find[i][j] == 0)
{
nn++;
numIslands2(grid, i, j, nn, find);
}
}
}
return nn;
}
};
评论
发表评论