I’m trying to find the maximum area of an island within a matrix full of zeros or ones. Within this example:
My matrix would return 4 as the biggest island is made up of 4 ones.
[1,1,1],
[1,0,0],
[0,1,1]
When I’m calling my dfs function, I need to return the area of that island. At the same time, we’re converting all the ones that made up that island to zeros.
For some reason my variable “areaOfIsland” keeps receiving undefined from the function and I can’t figure out why? I’m learning recursion, BFS and DFS hoping someone can pinpoint what I’m missing here.
var maxAreaOfIsland = function (grid) {
let maxArea = 0;
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j] === 1) {
let areaOfIsland = dfs(grid, i, j);
console.log(areaOfIsland); //this keeps logging undefined.
if (areaOfIsland > maxArea) {
maxArea = areaOfIsland;
}
}
}
}
return maxArea;
};
const dfs = (matrix, i, j, area) => {
if (
i < 0 ||
j < 0 ||
i >= matrix.length ||
j >= matrix[0].length ||
matrix[i][j] === 0
) {
return area;
}
if (!area) area = 1;
area += 1;
matrix[i][j] = 0;
dfs(matrix, i + 1, j, area);
dfs(matrix, i - 1, j, area);
dfs(matrix, i, j + 1, area);
dfs(matrix, i, j - 1, area);
};