#3619
Count Islands With Total Value Divisible by K
MediumArrayDepth-First SearchBreadth-First SearchUnion-FindMatrixHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using DFS or BFS, we can efficiently find all islands while tracking their total values. We can mark cells as visited to avoid counting them multiple times.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a visited matrix to keep track of explored cells.
- 2Step 2: For each unvisited land cell, perform DFS/BFS to calculate the total value of the island and mark cells as visited.
- 3Step 3: Check if the total value is divisible by k and update the count accordingly.
solution.py16 lines
1def countIslands(grid, k):
2 def dfs(x, y):
3 if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]) or grid[x][y] <= 0:
4 return 0
5 total = grid[x][y]
6 grid[x][y] = -1
7 total += dfs(x+1, y) + dfs(x-1, y) + dfs(x, y+1) + dfs(x, y-1)
8 return total
9 count = 0
10 for i in range(len(grid)):
11 for j in range(len(grid[0])):
12 if grid[i][j] > 0:
13 total_value = dfs(i, j)
14 if total_value % k == 0:
15 count += 1
16 return countℹ
Complexity note: The time complexity is O(n) as we visit each cell once. The space complexity is O(n) due to the visited matrix.
- 1Islands are defined by 4-directional connectivity.
- 2The sum of island values must be checked for divisibility by k.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.