-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3619_Count_Islands_With_Total_Value_Divisible_by_K.py
More file actions
73 lines (46 loc) · 1.74 KB
/
3619_Count_Islands_With_Total_Value_Divisible_by_K.py
File metadata and controls
73 lines (46 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
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.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
0 <= grid[i][j] <= 106
1 <= k <= 106
"""
class Solution:
def countIslands(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
visited = [[False] * n for _ in range(m)]
def dfs(r, c):
if r < 0 or r >= m or c < 0 or c >= n:
return 0
if visited[r][c] or grid[r][c] <= 0:
return 0
visited[r][c] = True
total = grid[r][c]
total += dfs(r + 1, c)
total += dfs(r - 1, c)
total += dfs(r, c + 1)
total += dfs(r, c - 1)
return total
count = 0
for i in range(m):
for j in range(n):
if not visited[i][j] and grid[i][j] > 0:
island_sum = dfs(i, j)
if island_sum % k == 0:
count += 1
return count