Skip to content

3127. Make a Square with the Same Color 👍

  • Time: $O(mn)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  bool canMakeSquare(vector<vector<char>>& grid) {
    for (int i = 0; i < 2; ++i)
      for (int j = 0; j < 2; ++j) {
        int black = 0;
        int white = 0;
        for (int x = 0; x < 2; ++x)
          for (int y = 0; y < 2; ++y)
            if (grid[i + x][j + y] == 'B')
              ++black;
            else
              ++white;
        if (black >= 3 || white >= 3)
          return true;
      }
    return false;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public boolean canMakeSquare(char[][] grid) {
    for (int i = 0; i < 2; ++i)
      for (int j = 0; j < 2; ++j) {
        int black = 0;
        int white = 0;
        for (int x = 0; x < 2; ++x)
          for (int y = 0; y < 2; ++y)
            if (grid[i + x][j + y] == 'B')
              ++black;
            else
              ++white;
        if (black >= 3 || white >= 3)
          return true;
      }
    return false;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def canMakeSquare(self, grid: list[list[str]]) -> bool:
    for i in range(2):
      for j in range(2):
        black = 0
        white = 0
        for x in range(2):
          for y in range(2):
            if grid[i + x][j + y] == 'B':
              black += 1
            else:
              white += 1
        if black >= 3 or white >= 3:
          return True
    return False