Count Islands With Total Value Divisible by K Problem
Description
LeetCode Problem 3619.
You are given an m x n matrix grid and a positive integer k. An island is a group of positive integers (representing land) that are 4-directionally connected (horizontally or vertically).
The total value of an island is the sum of the values of all cells in the island.
Return the number of islands with a total value divisible by k.
Example 1:

Input: grid = [[0,2,1,0,0],[0,5,0,0,5],[0,0,1,0,0],[0,1,4,7,0],[0,2,0,0,8]], k = 5
Output: 2
Explanation:
The grid contains four islands. The islands highlighted in blue have a total value that is divisible by 5, while the islands highlighted in red do not.
Example 2:

Input: grid = [[3,0,3,0], [0,3,0,3], [3,0,3,0]], k = 3
Output: 6
Explanation:
The grid contains six islands, each with a total value that is divisible by 3.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 10001 <= m * n <= 10^50 <= grid[i][j] <= 10^61 <= k <= 10^6
Solution
Approach: Flood Fill
Scan the grid. Whenever we meet a positive cell, we have found a new island: explore all cells connected to it in four directions, add up their values, and zero each cell as we visit it so it is never counted twice. If the island's total is divisible by k, count it. We use an explicit stack instead of recursion because an island can contain up to 10^5 cells, which would overflow the call stack in some languages.
Complexity: O(m·n) time and O(m·n) space for the stack.
class Solution:
def countIslands(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
dirs = (-1, 0, 1, 0, -1)
ans = 0
for si in range(m):
for sj in range(n):
if not grid[si][sj]:
continue
s = grid[si][sj]
grid[si][sj] = 0
stack = [(si, sj)]
while stack:
i, j = stack.pop()
for d in range(4):
x, y = i + dirs[d], j + dirs[d + 1]
if 0 <= x < m and 0 <= y < n and grid[x][y]:
s += grid[x][y]
grid[x][y] = 0
stack.append((x, y))
if s % k == 0:
ans += 1
return ans