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.
1using System.Collections.Generic;
public class EqualRowColumn {
public static int EqualPairs(int[,] grid) {
int n = grid.GetLength(0);
var rowMap = new Dictionary<string, int>();
for (int i = 0; i < n; i++) {
string row = string.Join(",", Enumerable.Range(0, n).Select(j => grid[i, j]));
if (!rowMap.ContainsKey(row))
rowMap[row] = 0;
rowMap[row]++;
}
int count = 0;
for (int j = 0; j < n; j++) {
string col = string.Join(",", Enumerable.Range(0, n).Select(i => grid[i, j]));
if (rowMap.ContainsKey(col)) {
count += rowMap[col];
}
}
return count;
}
public static void Main() {
int[,] grid = { { 3, 2, 1 }, { 1, 7, 6 }, { 2, 7, 7 } };
Console.WriteLine(EqualPairs(grid));
}
}
The C# implementation uses a dictionary to hash and save rows converted to strings, then checks these against columns walked in sequence, totaling equal pairs when matches appear.