#2579
Medium Algorithms Count total number of colored cells
Math
66.1% acceptance
Feb 25, 2026
845
95
There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer n, indicating that you must do the following routine for n minutes:
At the first minute, color any arbitrary unit cell blue.
Every minute thereafter, color blue every uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
Return the number of colored cells at the end of n minutes.
Solution
Rust
Time O(1)
Space O(1)
impl Solution {
pub fn colored_cells(n: i32) -> i64 {
// Formula: 1 + 2*n*(n-1) = 2n^2 - 2n + 1
let n = n as i64;
2 * n * n - 2 * n + 1
}
}