矩陣中 4 個相鄰元素的最大積(C++)


在本教程中,我們將討論一個程式,以查詢矩陣中 4 個相鄰元素的最大乘積。

為此,將為我們提供一個方陣。我們的任務是找出四個相鄰元素的最大乘積,這些元素可以是上、下、右、左或對角線。

示例

 現場演示

#include <bits/stdc++.h>
using namespace std;
const int n = 5;
//finding maximum product
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;
         }
         //checking in vertical row
         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;
         }
         //checking in diagonal
         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 - 1) <= 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;
         }
      }
   }
   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

更新於: 09-9 月-2020

213 次觀看

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.