educative.io

Optimizing solution for Number of Islands

Can we remove the following (commented) lines in the provided solution?

from union_find import UnionFind

def num_islands(grid):
    if not grid:
        return 0

    cols = len(grid[0])
    rows = len(grid)
    union_find = UnionFind(grid)

    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '1':
                # grid[r][c] = '0'

                # if r - 1 >= 0 and grid[r - 1][c] == '1':
                #     union_find.union(r * cols + c, (r - 1) * cols + c)
                if r + 1 < rows and grid[r + 1][c] == '1':
                    union_find.union(r * cols + c, (r + 1) * cols + c)
                # if c - 1 >= 0 and grid[r][c - 1] == '1':
                #     union_find.union(r * cols + c, r * cols + c - 1)
                if c + 1 < cols and grid[r][c + 1] == '1':
                    union_find.union(r * cols + c, r * cols + c + 1)

    count = union_find.get_count()
    return count

Course: Grokking Coding Interview Patterns in Python - AI-Powered Learning for Developers
Lesson: Solution: Number of Islands - Grokking Coding Interview Patterns in Python

1 Like

Hello @Isaac_Haseley,

Yes we can indeed remove the lines commented out in the provided code. Thank you for pointing this out.

We’ll incorporate this suggestion in the coming iterations. You’ll be able to see the updates soon. Please feel free to share further suggestions and feedback. We’d be happy to help!

1 Like