C++ Online Compiler
Example: Brute-Force Max Ones Row in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Brute-Force Max Ones Row #include <iostream> #include <vector> // Using std::vector for dynamic arrays #include <algorithm> // For std::max, not strictly necessary but useful using namespace std; // Function to find the row with maximum 1s using brute-force int findMaxOnesRowBruteForce(const vector<vector<int>>& matrix) { int rows = matrix.size(); if (rows == 0) { return -1; // Handle empty matrix } int cols = matrix[0].size(); if (cols == 0) { return -1; // Handle empty rows } int maxOnesCount = 0; int maxOnesRowIndex = -1; // Step 1: Iterate through each row for (int i = 0; i < rows; ++i) { int currentOnesCount = 0; // Step 2: Iterate through each element in the current row for (int j = 0; j < cols; ++j) { if (matrix[i][j] == 1) { currentOnesCount++; } } // Step 3: Check if current row has more 1s than the maximum found so far if (currentOnesCount > maxOnesCount) { maxOnesCount = currentOnesCount; maxOnesRowIndex = i; } } return maxOnesRowIndex; } int main() { // Example Matrix 1 vector<vector<int>> matrix1 = { {0, 1, 1, 1}, {0, 0, 1, 1}, {1, 1, 1, 1}, {0, 0, 0, 0} }; // Example Matrix 2 (all zeros) vector<vector<int>> matrix2 = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} }; // Example Matrix 3 (all ones) vector<vector<int>> matrix3 = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1} }; // Step 1: Test with matrix1 cout << "Matrix 1:" << endl; for (const auto& row : matrix1) { for (int val : row) { cout << val << " "; } cout << endl; } cout << "Row with max 1s (Brute Force): " << findMaxOnesRowBruteForce(matrix1) << endl << endl; // Step 2: Test with matrix2 cout << "Matrix 2:" << endl; for (const auto& row : matrix2) { for (int val : row) { cout << val << " "; } cout << endl; } cout << "Row with max 1s (Brute Force): " << findMaxOnesRowBruteForce(matrix2) << endl << endl; // Step 3: Test with matrix3 cout << "Matrix 3:" << endl; for (const auto& row : matrix3) { for (int val : row) { cout << val << " "; } cout << endl; } cout << "Row with max 1s (Brute Force): " << findMaxOnesRowBruteForce(matrix3) << endl << endl; return 0; }
Output
Clear
ADVERTISEMENTS