- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Matrix Traversal and Manipulation
Matrix and 2D Arrays
Matrix Traversal and Manipulation
Grid problems are graph problems with implicit edges. Before any of that, though, you have to create the grid correctly - and the obvious way is wrong.
The bug to get out of the way first
Every row is the same array
javascript
// WRONG — fill() copies the reference, not the array.
const grid = new Array(3).fill(new Array(3).fill(0))
grid[0][0] = 1
console.log(grid)
// [[1,0,0], [1,0,0], [1,0,0]] — all three rows changed
// RIGHT — a fresh array per row.
const grid2 = Array.from({ length: 3 }, () => new Array(3).fill(0))
grid2[0][0] = 1
console.log(grid2)
// [[1,0,0], [0,0,0], [0,0,0]]