Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Why does my recursive search function keep returning undefined?

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);
};

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!