I'm trying to create a 2D array visited to show where the code has already visited in the grid. The way I have it now is that each row in visited is a shallow copy. Changing the value in one row, changes in all of the rows. What's the best way to initialize the starting values in visited in this case?
let grid =
[
["0", "1", "0"],
["1", "0", "1"],
["0", "1", "0"],
]
let visited = new Array(grid.length).fill(new Array(grid[0].length).fill(false))
visited[0][1]= true
console.log(visited);
Output:
[
[ false, true, false ],
[ false, true, false ],
[ false, true, false ]
]
You can use map to create new array for each row
let grid =
[
["0", "1", "0"],
["1", "0", "1"],
["0", "1", "0"],
]
let visited = Array.from({length: grid.length}, () => Array(grid[0].length).fill(false))
visited[0][1]= true
console.log(visited);
Also you can replace new Array() with Array.from
i.e Array.from({length: grid.length}, () => Array(grid[0].length).fill(false))