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 byk.
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.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
0 <= grid[i][j] <= 106
1 <= k <= 106
Solutions
Solution 1: DFS
We define a function \(\textit{dfs}(i, j)\), which performs DFS traversal starting from position \((i, j)\) and returns the total value of that island. We add the current position's value to the total value, then mark that position as visited (for example, by setting its value to 0). Next, we recursively visit the adjacent positions in four directions (up, down, left, right). If an adjacent position has a value greater than 0, we continue the DFS and add its value to the total value. Finally, we return the total value.
In the main function, we traverse the entire grid. For each unvisited position \((i, j)\), if its value is greater than 0, we call \(\textit{dfs}(i, j)\) to calculate the total value of that island. If the total value is divisible by \(k\), we increment the answer by one.
The time complexity is \(O(m \times n)\), and the space complexity is \(O(m \times n)\), where \(m\) and \(n\) are the number of rows and columns of the grid, respectively.