1. Description
Given an m x n matrix grid and a positive integer k, treat cells with positive values as land and cells containing 0 as water.
An island is a maximal group of land cells connected horizontally or vertically. Its total value is obtained by adding the values of every cell in the group.
Count the islands whose total value is divisible by k.
2. Example
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 four islands have total values 8, 5, 15, and 8. Only 5 and 15 are divisible by 5.
Example 2
Input: grid = [[3,0,3,0],[0,3,0,3],[3,0,3,0]], k = 3
Output: 6
Explanation: Each positive cell forms its own island. All six islands have total value 3, so all are counted.
3. Constraints
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 1000
- 1 <= m * n <= 10$^5$
- 0 <= grid[i][j] <= 10$^6$
- 1 <= k <= 10$^6$
4. Solutions
Breadth-First Search
m = grid.size(), n = grid.front().size()
Time complexity: O(mn)
Space complexity: O(mn)
| |