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.
1using System;
2
3public class Program {
4 public static int EqualPairs(int[,] grid) {
5 int n = grid.GetLength(0);
6 int count = 0;
7 for (int i = 0; i < n; i++) {
8 for (int j = 0; j < n; j++) {
9 bool isEqual = true;
10 for (int k = 0; k < n; k++) {
11 if (grid[i, k] != grid[k, j]) {
12 isEqual = false;
13 break;
14 }
15 }
16 if (isEqual) count++;
17 }
18 }
19 return count;
20 }
21
22 public static void Main() {
23 int[,] grid = { { 3, 2, 1 }, { 1, 7, 6 }, { 2, 7, 7 } };
24 Console.WriteLine(EqualPairs(grid));
25 }
26}
This C# solution follows the same nested loop approach to count pairs where the row matches the column via element comparison, increasing count for each successful match.
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
The Python code uses a Counter to hash rows as tuple keys, allowing quick comparison with columns formed as tuples; the count increments with matches based on row-hash frequency.