Count Islands on a Torus
You are given a grid of 0 (water) and 1 (land) laid out on a torus: the top row is adjacent to the bottom row, and the leftmost column is adjacent to the rightmost column. Two land cells belong to the same island when they share a side, including across those wrapped edges.
Return the number of islands.
[[1, 0, 1], [0, 0, 0], -> 1 // the four corners touch through the edges [1, 0, 1]] [[1, 0, 0, 1], [0, 1, 0, 0]] -> 2
Up to 300 rows and 300 columns. Follow-ups: give a second, different approach, analyse both, and then support a stream of single-cell flips, reporting the island count after each.
Hints
Hint 1
The only change from the flat problem is how a neighbour is computed: (r + dr + rows) % rows and (c + dc + cols) % cols.
Hint 2
Use an explicit stack or queue rather than recursion; 90,000 land cells in one island would overflow the call stack.
Hint 3
For the second approach, union each land cell with its right and down neighbours, wrapping, and count the distinct roots.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.