알고리즘/LeetCode
2352. Equal Row and Column Pairs
앤테바
2022. 12. 23. 22:19
반응형
문제)
2352. Equal Row and Column Pairs
Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
Example 1:
Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
Output: 1
Explanation: There is 1 equal row and column pair:
- (Row 2, Column 1): [2,7,7]
Example 2:
Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
Output: 3
Explanation: There are 3 equal row and column pairs:
- (Row 0, Column 0): [3,1,2,2]
- (Row 2, Column 2): [2,4,2,2]
- (Row 3, Column 2): [2,4,2,2]
Constraints:
- n == grid.length == grid[i].length
- 1 <= n <= 200
- 1 <= grid[i][j] <= 105
솔루션1)
- 해시를 사용한다
- 행에 대해서 문자열 키를 생성해서 해시 자료구조를 생성한다.
- 열에 대해서 문자열 키를 생성해서 해시 자료구조를 생성한다.
- 키가 동일할 수 있으므로 value는 int이며 count를 갖는다.
- row 키를 순회하면 col에 매칭되는 키가 있으면 각 count만큼 곱해주면 그것이 row와 col이 매칭되는 수이다.
class Solution:
def equalPairs(self, grid: List[List[int]]) -> int:
row_key = defaultdict(int)
for row in grid:
key = ','.join([str(v) for v in row])
row_key[key] += 1
grid = list(zip(*grid))
col_key = defaultdict(int)
for col in grid:
key = ','.join([str(v) for v in col])
col_key[key] += 1
return sum([row_key[key] * col_key[key] for key in row_key if key in col_key])
반응형