Problem Description
Given a 3 x 3 grid consisting of characters 'B' (black) and 'W' (white), determine if it is possible to form a 2 x 2 subgrid with all cells of the same color by changing the color of at most one cell.
Key Insights
- There are only four possible 2 x 2 subgrids in a 3 x 3 grid.
- For each subgrid, count the number of 'B' and 'W' cells.
- If any subgrid has at least 3 cells of the same color, you can change the remaining cell (if needed) to form a uniform 2 x 2 square.
- Check each subgrid and return true as soon as a valid configuration is found.
Space and Time Complexity
Time Complexity: O(1) – There is a fixed number of subgrids (4 subgrids) and each checks 4 cells. Space Complexity: O(1) – A constant amount of extra space is used.
Solution
The approach is to enumerate all 2 x 2 subgrids starting at positions (0,0), (0,1), (1,0), and (1,1). For each subgrid, count how many 'B' and 'W' cells there are. If either count is 3 or 4, then with at most one change you can have a uniform square. Otherwise, move on to the next subgrid. Return true if any subgrid can be made uniform, and false if none qualify.