C++ Online Compiler
Example: Brute-Force Sum of KxK Sub-squares in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Brute-Force Sum of KxK Sub-squares #include <iostream> #include <vector> void findKxKSubsquareSumsBruteForce(const std::vector<std::vector<int>>& matrix, int N, int K) { if (K <= 0 || K > N) { std::cout << "Invalid K value. K must be between 1 and N." << std::endl; return; } std::cout << "Sums of KxK sub-squares (Brute-Force):" << std::endl; // Iterate through all possible top-left corners (i, j) of KxK sub-squares // The top-left row 'i' can go from 0 to N-K // The top-left column 'j' can go from 0 to N-K for (int i = 0; i <= N - K; ++i) { for (int j = 0; j <= N - K; ++j) { int currentSubsquareSum = 0; // Iterate through the elements within the current KxK sub-square for (int row = i; row < i + K; ++row) { for (int col = j; col < j + K; ++col) { currentSubsquareSum += matrix[row][col]; } } std::cout << currentSubsquareSum << " "; } } std::cout << std::endl; } int main() { // Step 1: Define the matrix and its dimensions int N = 3; // Matrix size N x N int K = 2; // Sub-square size K x K std::vector<std::vector<int>> matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Step 2: Call the brute-force function findKxKSubsquareSumsBruteForce(matrix, N, K); // Another example N = 4; K = 3; std::vector<std::vector<int>> matrix2 = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4} }; findKxKSubsquareSumsBruteForce(matrix2, N, K); return 0; }
Output
Clear
ADVERTISEMENTS