Imagine I need to generate a 2D array with this specific structure:
[0, 1, 1, 1]
[1, 0, 0, 0]
[1, 0, 0, 0]
To achieve this, I first initialized a 2D array with 0
values:
function createGrid(m: number, n: number): number {
let grid: number[][] = new Array(m).fill(0).map(() => new Array(n).fill(0));
return 0;
};
Next, I updated the values in the first row (except for grid[0][0]
) to be 1
:
function uniquePaths(m: number, n: number): number {
let grid: number[][] = new Array(m).fill(0).map(() => new Array(n).fill(0));
for (let i = 1; i <= m; i++) {
grid[0][i] = 1;
}
return 0;
};
Similarly, I attempted to update the values in the first column (excluding grid[0][0]
) to 1
:
function uniquePaths(m: number, n: number): number {
let grid: number[][] = new Array(m).fill(0).map(() => new Array(n).fill(0));
for (let i = 1; i <= m; i++) {
grid[0][i] = 1;
}
for (let i = 1; i <= n; i++) {
grid[i][0] = 1; // <<-- 'Throws error here`
}
return 0;
};
Unfortunately, an error is thrown stating:
grid[i] is undefined
I'm confused about what might be causing this. Any explanations would be greatly appreciated.