Ninja technique🥷 to ACE DSA Interviews.
For each cell we check, if it is 1,then we call a Dfs on it
DFS Function:
Complexity:
class Solution{
private:
int dfs(vector<vector<int>> &grid, int i, int j){
int r = grid.size();
int c = grid[0].size();
if (i >= 0 && j >= 0 && i < r && j < c && grid[i][j] == 1){
grid[i][j] = 0;
return 1 + dfs(grid, i + 1, j) + dfs(grid, i - 1, j)
+ dfs(grid, i, j + 1) + dfs(grid, i, j - 1);
}
return 0;
}
public:
int maxAreaOfIsland(vector<vector<int>> &grid){
int r = grid.size();
int c = grid[0].size();
int ans = 0;
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
if (grid[i][j] == 1)
ans = max(ans, dfs(grid, i, j));
return ans;
}
};
class Solution{
private:
int dfs(vector<vector<int>> &grid, int i, int j){
int r = grid.size();
int c = grid[0].size();
int area = 1;
vector<int> dir({-1, 0, 1, 0, -1});
grid[i][j] = 0;
// dfs on 4 directions
for (int k = 0; k < 4; k++){
int nr = i + dir[k], nc = j + dir[k + 1];
if (nr >= 0 && nc >= 0 && nr < r && nc < c && grid[nr][nc] == 1)
area += dfs(grid, nr, nc);
}
return area;
}
public:
int maxAreaOfIsland(vector<vector<int>> &grid){
int r = grid.size(), c = grid[0].size(), ans = 0;
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
if (grid[i][j] == 1)
ans = max(ans, dfs(grid, i, j));
return ans;
}
};
For each cell we check, if it is 1,then we call a bsf on it
BFS Function
grid[nr][nc]=0
and increase the area count.Complexity:
class Solution{
public:
int maxAreaOfIsland(vector<vector<int>> &grid){
int r = grid.size(), c = grid[0].size(), ans = 0;
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
if (grid[i][j] == 1)
ans = max(ans, bfs(grid, i, j));
return ans;
}
private:
int bfs(vector<vector<int>> &grid, int i, int j){
int r = grid.size();
int c = grid[0].size();
int area = 1;
vector<int> dir({-1, 0, 1, 0, -1});
grid[i][j] = 0;
// queue for bfs
queue<pair<int, int>> q;
q.push({i, j});
while (!q.empty()){
int z = q.front().first, x = q.front().second;
q.pop();
// move in 4 directions
for (int k = 0; k < 4; k++){
int nr = z + dir[k], nc = x + dir[k + 1];
if (nr >= 0 && nc >= 0 && nr < r && nc < c && grid[nr][nc] == 1){
grid[nr][nc] = 0;
area++;
q.push({nr, nc});
}
}
}
return area;
}
};