闯关leetcode——3127. Make a Square with the Same Color

题目

地址

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:

BWB
BWW
BWB

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:

BWB
WBW
BWB

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:

BWB
BWW
BWW

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

breaksoftware

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值