I was working on this Leetcode problem Longest Line of Consecutive One in Matrix subscription required, but I cannot figure out why I get an error with regards to indexing. That is, Line 15: TypeError: Cannot set property '0' of undefined
.
What's up with this bug?
/**
* @param {number[][]} M
* @return {number}
*/
var longestLine = function(M) {
if(!M.length) return 0;
let ones = 0;
let dp = [[[]]];
for(let i=0; i<M.length; i++){
for(let j=0; j<M[0].length; j++){
if(M[i][j] === 1){
//dp[i][j] = undefined ? [] : dp[i][j];
console.log(dp);
dp[i][j][0] = i>0 ? dp[i-1][j][0] + 1 : 1; // ----> line 15 //left
dp[i][j][1] = j>0 ? dp[i][j-1][1] + 1 : 1; //right
dp[i][j][2] = (i > 0 && j > 0) ? dp[i-1][j-1][2]+1 : 1; //upper left
dp[i][j][3] = (i > 0 && j < M.length - 1) ? dp[i-1][j+1][3] + 1 : 1; //lower left
ones = Math.max(ones, dp[i][j][0], dp[i][j][1], dp[i][j][2], dp[i][j][3]);
}
}
}
return ones;
};