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

86
Views
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 answers
Answer question

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 Report
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!