2352. Equal Row and Column Pairs

Medium
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

解題

先建立 map 來儲存 相異 row 出現的次數,再與 column 進行比較和答案的加總。
func equalPairs(grid [][]int) int {
m := make(map[string]int)
res := 0
​
for i:=0; i<len(grid); i++ {
s := ""
for j:=0; j<len(grid[0]); j++ {
s += strconv.Itoa(grid[i][j])
s += "/"
}
​
m[s]++
}
​
for i:=0; i<len(grid[0]); i++ {
s := ""
for j:=0; j<len(grid); j++ {
s += strconv.Itoa(grid[j][i])
s += "/"
}
​
if m[s]!=0 {
res += m[s]
}
}
​
return res
}