Given a n x n
grid where each cell contains a character representing its color, determine if it is possible to make a square with equal sides using the same color. To create this square, one must choose any four identical corners in the grid. You are required to check if such a square can be formed. The grid is represented as a list of strings where each string is a row of the grid.
Example:
Input:
grid = [
"abba",
"aaaa",
"bbbb",
"bbaa"
]
Output:
True
n x n
, but actual constraints (e.g., maximum value for n
) need to be clear.For now, I’ll assume any character can be present and we’ll focus on finding any character’s matching square.
n x n
square’s top-left corner.def can_form_square(grid):
n = len(grid)
for i in range(n):
for j in range(n):
for k in range(1, n):
if i + k < n and j + k < n:
if (grid[i][j] == grid[i][j + k] and
grid[i][j] == grid[i + k][j] and
grid[i][j] == grid[i + k][j + k]):
return True
return False
# Example usage:
grid = [
"abba",
"aaaa",
"bbbb",
"bbaa"
]
print(can_form_square(grid)) # Output: True
The solution involves nested loops:
Time Complexity: O(n^3), where n
is the dimension of the grid: two loops for grid cells, and one for possible side lengths for each cell.
Thus this approach may work efficiently for small grids. For larger grids, optimization strategies could be considered.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?