1

when I init use fill to init a 2D array like this

    let dp = new Array(n);
    dp.fill(new Array(n).fill(false));

if I change the dp[0][0] it will be

[
  [ true, false, false, false, false ],
  [ true, false, false, false, false ],
  [ true, false, false, false, false ],
  [ true, false, false, false, false ],
  [ true, false, false, false, false ]
]

but if I use the below code to init a array, there is the result I need, what's the reason?

let dp = new Array(n);
for(let k = 0; k < n; k++){
    dp[k] = new Array(n).fill(false)
}
2

1 Answer 1

0

That happens because dp.fill() is using a reference to the same array, defined by new Array(n).fill(false). When you change dp[0], you also "change" dp[1], dp[2], etc...

So you should use the code you posted below.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot for your help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.