Own Code:

class Solution:
    def equalPairs(self, grid: List[List[int]]) -> int:
        equal_counter = 0
        # dict for row elements
        dict_row = {}
        dict_col = {}
        for i in range(len(grid[0])):
            dict_row[i] = grid[i]
        
        # dict for col elements
        for i in range(len(grid)):
            dict_col[i] = []
            for j in range(len(grid[0])):
                dict_col[i].append(dict_row[j][i])
        
        for value_row in dict_row.values():
            for value_col in dict_col.values():
                if value_col == value_row:
                    equal_counter +=1
        return equal_counter

Better Code:

class Solution:
    def equalPairs(self, grid: List[List[int]]) -> int:
        equal_counter = 0
        
        # 遍历行
        for row in grid:
            # 遍历列
            for col in zip(*grid):  # 使用 zip(*grid) 获取每一列
                # 检查对应位置的元素是否相同
                if row == list(col):
                    equal_counter += 1
        
        return equal_counter

zip(*grid)zip() 函数可以将多个可迭代对象(如列表、元组等)中对应位置的元素打包成元组并返回一个迭代器。在这里,*grid 是将二维列表 grid 解包,相当于将每个内部列表作为参数传递给 zip() 函数。因此,zip(*grid) 实际上是将 grid 中的每一列的元素打包成元组。