About two weeks ago I met the “number of islands” problem in LeetCode. The first idea that jumped out of my brain is ‘dynamic programming’: I can create a new matrix (let’s name it ‘number matrix’) with the same size as the problem matrix, and set every position a value. The value is the number of islands from (0, 0) to this position.

For example, as the below problem matrix:

1111
0000
1011
0000
problem matrix

We can create the ‘number matrix’:

1111
1111
2233
2233
number matrix

Why the (4, 0) position in ‘number matrix’ is 2? Because the (0, 0) to (4, 0) area in ‘problem matrix’ has two islands:

1
0
1
0
(0, 0) to (4, 0) area of ‘problem matrix’

Then, every time we want to calculate the value of a position in the ‘number matrix’ we can first calculate the values of its ‘left’, ‘top’ and ‘left-top’ position.

For example, since the (3, 3), (4, 3) and (3, 4) positions in the ‘number matrix’ are all ‘3’, and the (4, 4) position in ‘problem matrix’ is ‘0’, the (4, 4) position of ‘number matrix’ should be ‘3’ also.

But unfortunately, after two weeks of struggling on thinking, I finally found out that the value of a position in the ‘number matrix’ can’t be decided by its nearest three positions: left, top and left-top. The counterexample is below:

1111111
0000001
1111101
1000101
1010101
1011101
1111111
problem matrix A

Let’s just build the number matrix for the (6, 6) to (7, 7) area of problem matrix A:

22
2

Don’t rush. Let’s look at another problem matrix:

11111
10001
10101
10001
11111
problem matrix B

This time, we also build the number matrix for the (4, 4) to (5, 5) area of problem matrix B:

22
2

See? They have the same values for left, top and left-top, but different final results (problem matrix A has just 1 island but problem matrix B has 2).

Two weeks of hard thinking just got the wrong idea. But this is the charming of algorithm 🙂