2

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;
};
10
  • shouldn't M[0].length be M[i].length Commented Feb 8, 2019 at 19:19
  • 3
    You've declared dp to be a 3D array where each dimension has a length of 1. Whenever i or j are anything other than 0, dp[i][j] is going to be referring to an element in one or both of the first two dimensions that doesn't exist. Therefore, dp[i][j] is going to be undefined, so dp[i][j][0] is going to throw an error. Commented Feb 8, 2019 at 19:19
  • So how do you declare a full 3D array? Commented Feb 8, 2019 at 19:34
  • Just initialize dp[i][j] = []. Commented Feb 8, 2019 at 19:44
  • Possible duplicate of How to create a multi dimensional array in Javascript? Commented Feb 8, 2019 at 19:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.