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 生成算了)
|
|
Scala
最近在学 Scala,于是自然又用 Scala 写一次。相比于此前丑陋的 if 判断,干脆写得更加函数式,试一下 loop free。
直接三行搞定。
|
|