[LeetCode] 2352. Equal Row and Column Pairs(Kotlin)
풀이
// input
grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
// values
rowMap: {0=[3, 1, 2, 2], 1=[1, 4, 4, 5], 2=[2, 4, 2, 2], 3=[2, 4, 2, 2]}
colMap: {0=[3, 1, 2, 2], 1=[1, 4, 4, 4], 2=[2, 4, 2, 2], 3=[2, 5, 2, 2]}
rowCountMap: {[3, 1, 2, 2]=1, [1, 4, 4, 5]=1, [2, 4, 2, 2]=2}
colCountMap: {[3, 1, 2, 2]=1, [1, 4, 4, 4]=1, [2, 4, 2, 2]=1, [2, 5, 2, 2]=1}
// output
3
class Solution {
fun equalPairs(grid: Array<IntArray>): Int {
val n = grid.size
val rowMap: MutableMap<Int, String> = mutableMapOf()
val colMap: MutableMap<Int, String> = mutableMapOf()
for(r in 0 until n){
rowMap[r] = grid[r].toList().toString()
}
for(c in 0 until n){
colMap[c] = mutableListOf<Int>().apply{
for(r in 0 until n) add(grid[r][c])
}.toString()
}
val rowCountMap = rowMap.values.groupingBy{it}.eachCount()
val colCountMap = colMap.values.groupingBy{it}.eachCount()
var answer: Int = 0
for(row in rowCountMap.keys){
if(colCountMap.containsKey(row)){
answer += rowCountMap[row]!! * colCountMap[row]!!
}
}
return answer
}
}