LeetCode 题解工作台

构造相同颜色的正方形

给你一个二维 3 x 3 的矩阵 grid ,每个格子都是一个字符,要么是 'B' ,要么是 'W' 。字符 'W' 表示白色,字符 'B' 表示黑色。 你的任务是改变 至多一个 格子的颜色,使得矩阵中存在一个 2 x 2 颜色完全相同的正方形。 如果可以得到一个相同颜色的 2 x 2 正方形,那么…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·matrix

bolt

答案摘要

我们可以枚举每个 $2 \times 2$ 的正方形,统计黑色和白色的个数,如果两者个数不相等,那么就可以构造一个相同颜色的正方形,返回 `true`。 否则,遍历结束后返回 `false`。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二维 3 x 3 的矩阵 grid ,每个格子都是一个字符,要么是 'B' ,要么是 'W' 。字符 'W' 表示白色,字符 'B' 表示黑色。

你的任务是改变 至多一个 格子的颜色,使得矩阵中存在一个 2 x 2 颜色完全相同的正方形。

如果可以得到一个相同颜色的 2 x 2 正方形,那么返回 true ,否则返回 false 。

 

示例 1:

 
 
 
 
 
 
 
 
 

输入:grid = [["B","W","B"],["B","W","W"],["B","W","B"]]

输出:true

解释:

修改 grid[0][2] 的颜色,可以满足要求。

示例 2:

 
 
 
 
 
 
 
 
 

输入:grid = [["B","W","B"],["W","B","W"],["B","W","B"]]

输出:false

解释:

只改变一个格子颜色无法满足要求。

示例 3:

 
 
 
 
 
 
 
 
 

输入:grid = [["B","W","B"],["B","W","W"],["B","W","W"]]

输出:true

解释:

grid 已经包含一个 2 x 2 颜色相同的正方形了。

 

提示:

  • grid.length == 3
  • grid[i].length == 3
  • grid[i][j] 要么是 'W' ,要么是 'B'
lightbulb

解题思路

方法一:枚举

我们可以枚举每个 2×22 \times 2 的正方形,统计黑色和白色的个数,如果两者个数不相等,那么就可以构造一个相同颜色的正方形,返回 true

否则,遍历结束后返回 false

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def canMakeSquare(self, grid: List[List[str]]) -> bool:
        for i in range(0, 2):
            for j in range(0, 2):
                cnt1 = cnt2 = 0
                for a, b in pairwise((0, 0, 1, 1, 0)):
                    x, y = i + a, j + b
                    cnt1 += grid[x][y] == "W"
                    cnt2 += grid[x][y] == "B"
                if cnt1 != cnt2:
                    return True
        return False
speed

复杂度分析

指标
时间complexity is O(1) because the grid is always 3x3 and only four 2x2 squares exist. Space complexity is O(1) since no extra data structures proportional to input size are used.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Checks your ability to enumerate submatrices efficiently.

  • question_mark

    Tests pattern recognition in small fixed-size matrices.

  • question_mark

    Looks for handling edge cases where a single change is insufficient.

warning

常见陷阱

外企场景
  • error

    Forgetting to check all four 2x2 submatrices in the 3x3 grid.

  • error

    Failing to count differing cells correctly within each square.

  • error

    Returning true when two or more cells differ in a 2x2 square.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider larger NxN grids where you want to form KxK squares of the same color.

  • arrow_right_alt

    Allow changing more than one cell and check minimal changes required to form a uniform square.

  • arrow_right_alt

    Modify the problem to count how many distinct 2x2 uniform squares can be formed after at most one change.

help

常见问题

外企场景

构造相同颜色的正方形题解:数组·matrix | LeetCode #3127 简单