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

问题可以转化成判断 matrix 是否存在一个 2 * 2 的 matrix,其中包含 3 or 4 个相同的元素。

但是再仔细一看 matrix 只有 3 * 3,因此可以直接分成 4 个 block,分别判断 4 个 block 是否存在就行了。

Kotlin

直接判断每一个点分别在哪些 block 里面,但是这几个 if 判断就写得很丑陋(写了一个之后干脆打开 GitHub Copilot 生成算了)

 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

最近在学 Scala,于是自然又用 Scala 写一次。相比于此前丑陋的 if 判断,干脆写得更加函数式,试一下 loop free。

直接三行搞定。

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
    }
}