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

129
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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