You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++二维数组每行元素一致性检测算法及代码需求

C++ Algorithm to Check Uniform Rows in a 2D Matrix

Got it, let's work through this problem together. You need a C++ solution that scans a 2D matrix and returns 1 if any row has non-identical elements, and 0 if every row's elements are all the same.

Approach

The core idea here is to optimize for early termination—no need to check the entire matrix once we find a row that fails the test. Here's the step-by-step logic:

  • Iterate over each row in the matrix.
  • For each row, take the first element as a reference value (we’ll handle edge cases like empty rows/matrix too).
  • Compare every other element in the row to this reference.
  • If any element doesn’t match the reference, immediately return 1—no need to check further rows.
  • If all rows pass the check (all elements in every row are identical), return 0.

C++ Code Implementation

Here's a clean, efficient implementation with comments:

#include <vector>

int checkUniformRows(const std::vector<std::vector<int>>& matrix) {
    // Handle edge case: empty matrix
    if (matrix.empty()) {
        return 0; // Adjust this if your requirement for empty input differs
    }

    for (const auto& row : matrix) {
        // Handle edge case: empty row (treat as uniform here)
        if (row.empty()) {
            continue;
        }

        int reference = row[0];
        for (size_t i = 1; i < row.size(); ++i) {
            if (row[i] != reference) {
                // Found a non-uniform row, exit early
                return 1;
            }
        }
    }

    // All rows are fully uniform
    return 0;
}

// Example usage
#include <iostream>
int main() {
    // Example 1 matrix (returns 1)
    std::vector<std::vector<int>> matrix1 = {
        {0, 1, 2, 3},
        {0, 2, 1, 4}, // This row has mismatched elements (1 vs 4)
        {4, 2, 6, 3}
    };
    std::cout << checkUniformRows(matrix1) << std::endl; // Output: 1

    // Example of a fully uniform matrix (returns 0)
    std::vector<std::vector<int>> matrix2 = {
        {5,5,5},
        {2,2},
        {9,9,9,9}
    };
    std::cout << checkUniformRows(matrix2) << std::endl; // Output: 0

    return 0;
}

Example Breakdown

Let’s walk through your first example:

Example1矩阵:
0 1 2 3
0 2 1 4
4 2 6 3

When the code processes the second row ({0,2,1,4}), it takes 0 as the reference value. As soon as it hits 2 (which doesn’t match 0), or later 1 and 4, it immediately stops checking and returns 1—this saves unnecessary computation on the rest of the matrix.

For a matrix where every row’s elements are identical, the code will loop through all rows, confirm all elements match the first in their row, and finally return 0.

内容的提问来源于stack exchange,提问作者Toms lns

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:43:20