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).
?
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]
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]
From: LeetCode
Link: 2352. Equal Row and Column Pairs
This function counts the number of equal pairs by comparing each row with each column. If the elements in a row and column match for the entire length, it increments the count. This solution has a time complexity of O ( n 3 ) O(n^3) O(n3) which is acceptable given the constraints 1 ≤ n ≤ 200 1≤n≤200 1≤n≤200.
int equalPairs(int** grid, int gridSize, int* gridColSize) {
int count = 0;
for (int i = 0; i < gridSize; ++i) { // Iterate over rows
for (int j = 0; j < gridSize; ++j) { // Iterate over columns
int k;
for (k = 0; k < gridSize; ++k) { // Check if row[i] equals column[j]
if (grid[i][k] != grid[k][j]) {
break; // If any element does not match, break out of the loop
}
}
if (k == gridSize) { // If we didn't break, the row and column are equal
count++;
}
}
}
return count;
}