LeetCode: Make a Square with the Same Color

Problem

source: 3127. Make a Square with the Same Color

difficulty: easy

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.

Constraints:

  • grid.length == 3
  • ``grid[i].length == 3`
  • grid[i][j] is either 'W' or 'B'.

Solution

The problem can be transformed into determining whether there exists a 2 * 2 matrix within a 3 * 3 matrix that contains 3 or 4 identical elements.

Given that the matrix is only 3 * 3, it can be directly divided into 4 blocks, and we can simply check whether any of these 4 blocks meet the condition.

Kotlin

Directly check which blocks each point belongs to. However, the if statements for these checks are quite ugly (after writing one, I ended up using GitHub Copilot to generate the rest).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    fun canMakeSquare(grid: Array<CharArray>): Boolean {
        val cnt = IntArray(4)
        fun Char.value(): Int = if (this == 'B') 1 else -1

        for (i in 0..2) {
            for (j in 0..2) {
                if ( i < 2 && j < 2) cnt[0] += grid[i][j].value()
                if ( i < 2 && j > 0) cnt[1] += grid[i][j].value()
                if ( i > 0 && j < 2) cnt[2] += grid[i][j].value()
                if ( i > 0 && j > 0) cnt[3] += grid[i][j].value()
            }
        }

        return cnt.any() { it in listOf(2, -2, 4, -4) }
    }
}

Scala

Recently, I've been learning Scala, so I naturally tried writing it in Scala again. Compared to the previous ugly if statements, I made it more functional and tried to make it loop-free.

I managed to do it in three lines.

1
2
3
4
5
6
7
8
9
object Solution {
    def canMakeSquare(grid: Array[Array[Char]]): Boolean = {
        def getRange = for { i <- 0 to 1; j <- 0 to 1} yield (i, j)

        def check(x: Int, y: Int): Boolean = getRange.count((i, j) => grid(x + i)(y + j) == 'B') != 2

        getRange.count((i, j) => check(i, j)) >= 1
    }
}