3127. Make a Square with the Same Color
SourceBiweekly Contest 129 Q1DifficultyEasyRating1337
Description
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.
Example 1:
Input: grid = [["B","W","B"],["B","W","W"],["B","W","B"]]
Output: true
Explanation:
It can be done by changing the color of the grid[0][2].
Example 2:
Input: grid = [["B","W","B"],["W","B","W"],["B","W","B"]]
Output: false
Explanation:
It cannot be done by changing at most one cell.
Example 3:
Input: grid = [["B","W","B"],["B","W","W"],["B","W","W"]]
Output: true
Explanation:
The grid already contains a 2 x 2 square of the same color.
Constraints:
grid.length == 3grid[i].length == 3grid[i][j]is either'W'or'B'.
Solutions
Solution 1: Enumeration
Thinking
The board is \(3\times 3\) and one recolor should create a monochrome \(2\times 2\). Trying every cell to flip is possible but less direct than inspecting each window.
A \(2\times 2\) that is already unbalanced (three of one color) becomes solid after one change; a solid window needs none. Both cases are exactly “black count \(\neq\) white count”.
Enumerate the four windows, count W and B, and return true on the first imbalance. The board size is constant.
We can enumerate each \(2 \times 2\) square, count the number of black and white cells. If the counts are not equal, then we can construct a square of the same color, and return true.
Otherwise, return false after the traversal.
The time complexity is \(O(1)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |