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 <iostream>
2#include <vector>
3using namespace std;
4
5int countEqualPairs(vector<vector<int>>& grid) {
6 int n = grid.size();
7 int count = 0;
8 for (int i = 0; i < n; ++i) {
9 for (int j = 0; j < n; ++j) {
10 bool equal = true;
11 for (int k = 0; k < n; ++k) {
12 if (grid[i][k] != grid[k][j]) {
13 equal = false;
14 break;
15 }
16 }
17 if (equal) ++count;
18 }
19 }
20 return count;
21}
22
23int main() {
24 vector<vector<int>> grid = {{3, 2, 1}, {1, 7, 6}, {2, 7, 7}};
25 cout << countEqualPairs(grid) << endl;
26 return 0;
27}
This C++ implementation checks each row and column for equality through three nested loops. If all elements in a row and column match, the count is incremented.
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
Java solution creates a hash map for rows as keys and then uses these keys to match columns converted to strings, considering multiple matching rows.