Sponsored
Sponsored
The straightforward way to solve the problem is by iteratively comparing each row with every column to determine if they are equal. This approach requires looping through each pair of row and column and verifying the elements one by one.
Time Complexity: O(n^3), as it involves comparing elements for each pair. Space Complexity: O(1), since no extra data structures are used except for counters.
1#include <stdio.h>
2int countEqualPairs(int n, int grid[n][n]) {
3 int count = 0;
4 for (int i = 0; i < n; i++) {
5 for (int j = 0; j < n; j++) {
6 int match = 1;
7 for (int k = 0; k < n; k++) {
8 if (grid[i][k] != grid[k][j]) {
9 match = 0;
10 break;
11 }
12 }
13 if (match) count++;
14 }
15 }
16 return count;
17}
18
19int main() {
20 int grid[3][3] = {{3, 2, 1}, {1, 7, 6}, {2, 7, 7}};
21 int result = countEqualPairs(3, grid);
22 printf("%d\n", result);
23 return 0;
24}
This C code iterates over each row and column pair and compares their elements. If a pair matches, it increments the count. The algorithm first checks each row against every column using two nested loops and a third loop for element-wise comparison.
By converting rows and columns into hashable objects (such as tuples in Python or strings in other languages), we can store their occurrences in a dictionary or a hash map. This facilitates a more efficient comparison by checking the presence of corresponding row and column hashes in the stored data structure.
Time Complexity: O(n^2) for transposing and additional O(n^3) for comparisons. Space Complexity: O(n^2) for storing the transposed matrix.
1#include <vector>
#include <unordered_map>
using namespace std;
typedef vector<int> vi;
int equalPairs(vector<vi>& grid) {
int n = grid.size();
unordered_map<string, int> rowMap;
for (int i = 0; i < n; ++i) {
string key = "";
for (int j = 0; j < n; ++j) {
key += to_string(grid[i][j]) + ",";
}
rowMap[key]++;
}
int count = 0;
for (int j = 0; j < n; ++j) {
string key = "";
for (int i = 0; i < n; ++i) {
key += to_string(grid[i][j]) + ",";
}
if (rowMap.count(key)) {
count += rowMap[key];
}
}
return count;
}
int main() {
vector<vector<int>> grid = {{3, 2, 1}, {1, 7, 6}, {2, 7, 7}};
cout << equalPairs(grid) << endl;
return 0;
}
Using unordered_map for hashing rows, this solution stores rows as hash keys and then checks columns against these keys. Each column conversion matches stored keys to count equal pairs.