Skip to main content
Back to problems
#3127
Easy Algorithms

Make a square with the same color

Array Matrix Enumeration
52.9% acceptance
Feb 23, 2026
94
11
You are given a 2D matrix grid of size 3 x 3 consisting only of characters 'B' and 'W'. Character 'W' represents the white color, and character 'B' represents the black color. Your task is to change the color of at most one cell so that the matrix has a 2 x 2 square where all cells are of the same color. Return true if it is possible to create a 2 x 2 square of the same color, otherwise, return false.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn can_make_square(grid: Vec<Vec<char>>) -> bool {
    // Check all 4 possible 2x2 squares
    for r in 0..2 {
      for c in 0..2 {
        let cells = [grid[r][c], grid[r][c+1], grid[r+1][c], grid[r+1][c+1]];
        let b_count = cells.iter().filter(|&&x| x == 'B').count();
        let w_count = 4 - b_count;
        // Can make all same color with at most 1 change: need 3 or 4 of same color
        if b_count >= 3 || w_count >= 3 {
          return true;
        }
      }
    }
    false
  }
}