LeetCode //C - 2352. Equal Row and Column Pairs

2024-01-03 09:02:09

2352. Equal Row and Column Pairs

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).
?

Example 1:

在这里插入图片描述

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]
Example 2:

在这里插入图片描述

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]
Constraints:
  • n == grid.length == grid[i].length
  • 1 <= n <= 200
  • 1 < = g r i d [ i ] [ j ] < = 1 0 5 1 <= grid[i][j] <= 10^5 1<=grid[i][j]<=105

From: LeetCode
Link: 2352. Equal Row and Column Pairs


Solution:

Ideas:

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 1n200.

Code:
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;
}

文章来源:https://blog.csdn.net/navicheung/article/details/135354047
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。