Approach
Breadth-first search
For Count Islands with Total Value Divisible by K, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 46 lines of C++ from the credited upstream file count-islands-with-total-value-divisible-by-k.cpp.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int countIslands(vector<vector<int>>& grid, int k) {8 static const vector<pair<int, int>> DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};9 10 const auto& bfs = [&](int i, int j) {11 if (!grid[i][j]) {12 return false;13 }14 int total = grid[i][j] % k;15 grid[i][j] = 0;16 vector<pair<int, int>> q = {{i, j}};17 while (!empty(q)) {18 vector<pair<int, int>> new_q;19 for (const auto& [i, j] : q) {20 for (const auto& [di, dj] : DIRECTIONS) {21 const int ni = i + di, nj = j + dj;22 if (!(0 <= ni && ni < size(grid) && 0 <= nj && nj < size(grid[0]) && grid[ni][nj])) {23 continue;24 }25 total = (total + grid[ni][nj]) % k;26 grid[ni][nj] = 0;27 new_q.emplace_back(ni, nj);28 }29 }30 q = move(new_q);31 }32 return total == 0;33 };34 35 int result = 0;36 for (int i = 0; i < size(grid); ++i) {37 for (int j = 0; j < size(grid[0]); ++j) {38 if (bfs(i, j)) {39 ++result;40 }41 }42 }43 return result;44 }45};46