Pages

21/06/2021

[Java] Delete islands

Given a matrix of zeros and ones, where groupings of ones represent land, delete all islands.
An island is a group of 1 or more ones which are NOT horizontally or vertically connected to a border.

Deleting an island means setting it to 0.

Example:
0001
1010
1000


should return:
0001
1000
1000


where only the lone 1 in the middle is deleted.

For each point in the borders that is a one, we start a DFS search for all horizontally or vertically connected ones, flipping all of them to -1.

We flag each point we add to the stack as soon as we add it to avoid putting duplicates in.

At the end of this search, we scan the whole matrix and restore the flipped ones while deleting the non flipped ones.

Complexity is O(NM) for both time and space. Worst case for space is when matrix is full of ones, therefore we fill the stack with almost all points in the matrix during the DFS.

You can check my implementation of deleteIslands on my Gist along with some tests in DeleteIslandsJTests.

No comments:

Post a Comment

With great power comes great responsibility