Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda