题目
地址
https://leetcode.com/problems/make-a-square-with-the-same-color/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:
| B | W | B |
|---|---|---|
| B | W | W |
| B | W | B |
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:
| B | W | B |
|---|---|---|
| W | B | W |
| B | W | B |
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:
| B | W | B |
|---|---|---|
| B | W | W |
| B | W | W |
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 == 3
- grid[i].length == 3
- grid[i][j] is either ‘W’ or ‘B’.
解题
这题就是要在一个33的矩阵中,检测是否存在最多只用改变一次颜色,就可以形成一个22的同色矩阵。
因为只存在2种颜色——Black和White,且只有4个位子,那么形成四个同色矩阵之前的状态如下:
- 已经同色
- 4个Black,0个White
- 4个White,0个Black
- 不同色
- 3个Black,1个White
- 1个Black,3个White
那么不能只改变一次颜色就能形成4个同色之前的状态是:
- 2个Black,2个White
我们只要检测一个格子周边是否存在2个同色格子即可判断“否”的场景,其他都是“是”的场景。
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
bool canMakeSquare(vector<vector<char>>& grid) {
for (int i = 0; i < grid.size() - 1; i++) {
for (int j = 0; j < grid[0].size() - 1; j++) {
int count = 0;
if (grid[i][j] == 'B') {
count++;
}
if (grid[i][j + 1] == 'B') {
count++;
}
if (grid[i + 1][j] == 'B') {
count++;
}
if (grid[i + 1][j + 1] == 'B') {
count++;
}
if (count != 2) {
cout << count <<endl;
return true;
}
}
}
return false;
}
};

代码地址
https://github.com/f304646673/leetcode/tree/main/3127-Make-a-Square-with-the-Same-Color/cplusplus
2417

被折叠的 条评论
为什么被折叠?



