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

136
Visualizações
no of islands problem using extra visited matrix

I done the implementation without using visited matrix which works fine, but to do no.of islands without changing input matrix i have used visited matrix , the answer is 4 but it is giving me result as 3 from below code

let grid=[['0','1','0'],['1','0','1'],['0','1','0']];
let visited=Array(grid.length).fill(Array(grid[0].length).fill(false));
let islands=0;
let check = (i,j) =>{
    if(i>=grid.length || j>=grid[0].length || i<0 || j<0 || visited[i][j] || grid[i][j]==='0')
        return 0;
    visited[i][j]=true;
    check(i+1,j);
    check(i,j+1);
    check(i-1,j);
    check(i,j-1);
};

for(let i=0;i<grid.length;i++)
    for(let j=0;j<grid[0].length;j++)
        if(grid[i][j]==='1' && !visited[i][j]){
            islands++;
            check(i,j);
        }
return islands;  
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If I define visited array as one of the following your code seems to work

visited=[[false,false,false],[false,false,false],[false,false,false]];

or following using How to fill multidimensional array in javascript?

function createAndFillTwoDArray({
  rows,
  columns,
  defaultValue
}){
  return Array.from({ length:rows }, () => (
      Array.from({ length:columns }, ()=> defaultValue)
   ))
}

var visited = createAndFillTwoDArray({rows:3, columns:3, defaultValue: false});
about 4 years ago · Juan Pablo Isaza Relatório
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