Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Maximum product of 4 adjacent elements in matrix in C++


ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมหาผลคูณสูงสุดของ 4 องค์ประกอบติดกันในเมทริกซ์

เราจะได้รับเมทริกซ์สี่เหลี่ยมจัตุรัส งานคือหาผลคูณสูงสุดของ 4 องค์ประกอบที่ติดกัน ซึ่งอาจเป็นแนวนอน แนวตั้ง แนวทแยงมุม

ตัวอย่างโค้ด

#include <bits/stdc++.h>
using namespace std;

const int n = 5;

int FindMaxProduct(int arr[][n], int n) {
    int max = 0, result;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            // แนวนอน (ซ้าย)
            if (j - 3 >= 0) {
                result = arr[i][j] * arr[i][j - 1] * arr[i][j - 2] * arr[i][j - 3];
                if (max < result) max = result;
            }
            // แนวตั้ง (บน)
            if (i - 3 >= 0) {
                result = arr[i][j] * arr[i - 1][j] * arr[i - 2][j] * arr[i - 3][j];
                if (max < result) max = result;
            }
            // ทแยงมุมซ้ายบน
            if (i - 3 >= 0 && j - 3 >= 0) {
                result = arr[i][j] * arr[i - 1][j - 1] * arr[i - 2][j - 2] * arr[i - 3][j - 3];
                if (max < result) max = result;
            }
            // ทแยงมุมขวาบน
            if (i - 3 >= 0 && j + 3 < n) {
                result = arr[i][j] * arr[i - 1][j + 1] * arr[i - 2][j + 2] * arr[i - 3][j + 3];
                if (max < result) max = result;
            }
        }
    }
    return max;
}

int main() {
    int arr[][5] = {
        {1, 2, 3, 4, 5},
        {6, 7, 8, 9, 1},
        {2, 3, 4, 5, 6},
        {7, 8, 9, 1, 0},
        {9, 6, 4, 2, 3}
    };
    cout << FindMaxProduct(arr, n);
    return 0;
}

เอาต์พุต

3024