Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda