Leetcode 3127: Make a Square with the Same Color

grid47
grid47
Exploring patterns and algorithms
Dec 30, 2023 6 min read

You are given a 3x3 matrix consisting of characters ‘B’ (black) and ‘W’ (white). Your task is to determine if it is possible to change the color of at most one cell to form a 2x2 square where all cells are of the same color. Return true if it is possible, otherwise return false.
Problem
Approach
Steps
Complexity
Input: The input consists of a 3x3 matrix where each cell contains either 'B' or 'W'.
Example: grid = [['B', 'W', 'B'], ['B', 'W', 'W'], ['B', 'W', 'B']]
Constraints:
• grid.length == 3
• grid[i].length == 3
• grid[i][j] is either 'W' or 'B'.
Output: Return true if it is possible to form a 2x2 square where all cells are of the same color, otherwise return false.
Example: Output: true
Constraints:
Goal: Determine if it's possible to form a 2x2 square of the same color by changing at most one cell.
Steps:
• 1. Loop through each possible 2x2 subgrid of the matrix.
• 2. Count the occurrences of 'B' and 'W' in each 2x2 subgrid.
• 3. Check if it's possible to change one cell to make all cells in the 2x2 subgrid the same color.
• 4. Return true if such a subgrid is found, otherwise return false.
Goal: The problem constraints define the size of the matrix and the allowable characters.
Steps:
• grid.length == 3
• grid[i].length == 3
• grid[i][j] is either 'W' or 'B'.
Assumptions:
• The input grid will always be a 3x3 matrix.
• The characters in the grid will always be 'B' or 'W'.
Input: grid = [['B', 'W', 'B'], ['B', 'W', 'W'], ['B', 'W', 'B']]
Explanation: By changing the color of grid[0][2] (B → W), we can create a 2x2 square with all cells the same color.

Input: grid = [['B', 'W', 'B'], ['W', 'B', 'W'], ['B', 'W', 'B']]
Explanation: No matter which cell we change, we can't form a 2x2 square with the same color.

Input: grid = [['B', 'W', 'B'], ['B', 'W', 'W'], ['B', 'W', 'W']]
Explanation: The matrix already contains a 2x2 square with all cells the same color (grid[1][1], grid[1][2], grid[2][1], grid[2][2]).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus