Problem solution · Python

Count Islands with Total Value Divisible by K

Count Islands with Total Value Divisible by K: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Breadth-first search
Source
Kamyu LeetCode Solutions
Length
33 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For Count Islands with Total Value Divisible by K, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 33 lines of Python from the credited upstream file count-islands-with-total-value-divisible-by-k.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeCount Islands with Total Value Divisible by K · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(m * n)# Space: O(m + n) # bfs, flood fillclass Solution(object):    def countIslands(self, grid, k):        """        :type grid: List[List[int]]        :type k: int        :rtype: int        """        DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))        def bfs(i, j):            if not grid[i][j]:                return False            total = grid[i][j]%k            grid[i][j] = 0            q = [(i, j)]            while q:                new_q = []                for i, j in q:                    for di, dj in DIRECTIONS:                        ni, nj = i+di, j+dj                        if not (0 <= ni < len(grid) and 0 <= nj < len(grid[0]) and grid[ni][nj]):                            continue                        total = (total+grid[ni][nj])%k                        grid[ni][nj] = 0                        new_q.append((ni, nj))                q = new_q            return total == 0         return sum(bfs(i, j) for i in xrange(len(grid)) for j in xrange(len(grid[0]))) 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗