'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;
Solution 1:[1]
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});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | algo_user |