3127. Make a Square with the Same Color

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public boolean canMakeSquare(char[][] grid) {
// 思路:以每个节点为左上角根节点进行扫描,统计出 2 * 2 正方形区域中的黑色格子、白色格子的个数
// 黑色 + 白色的所有组合方式:0 + 4, 1 + 3, 2 + 2, 3 + 1, 4 + 0, 可以观察出黑色或白色为 2 时无法满足题意

for (int i = 0; i < grid.length - 1; i++) {
for (int j = 0; j < grid[i].length - 1; j++) {
int whiteCount = whiteCount(grid[i][j]) + whiteCount(grid[i][j + 1]) + whiteCount(grid[i + 1][j]) + whiteCount(grid[i + 1][j + 1]);
if (whiteCount != 2) {
return true;
}
}
}

return false;
}

private int whiteCount(char c) {
return c == 'W' ? 1 : 0;
}
}

Reference

3127. Make a Square with the Same Color