用 C++ 檢查給定的矩陣是否是漢克爾矩陣


假如我們有一個方陣,我們的任務是檢查該矩陣是不是漢克爾矩陣。漢克爾矩陣是一種方陣,其中從左到右的每個遞增反對角線元素都是常數。假設一個矩陣如下所示 -

12345
23456
34567
45678
56789

要檢查矩陣是不是漢克爾矩陣,我們必須檢查 mat[i, j] = ai+j 是否成立。ai+j 可以定義為 -

$$a_{i+j}=\begin{cases}mat[i+j,0]< n\mat[i+j-n+1,n-1]otherwise\end{cases}$$

示例

 線上示例

#include <iostream>
#define N 5
using namespace std;
bool isHankelMat(int mat[N][N], int n) {
   for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
         if (i + j < n) {
            if (mat[i][j] != mat[i + j][0])
            return false;
         } else {
            if (mat[i][j] != mat[i + j - n + 1][n - 1])
            return false;
         }
      }
   }
   return true;
}
int main() {
   int n = 5;
   int mat[N][N] = {
      { 1, 2, 3, 4, 5},
      { 2, 3, 4, 5, 6},
      { 3, 4, 5, 6, 7},
      { 4, 5, 6, 7, 8},
      { 5, 6, 7, 8, 9}
   };
   if(isHankelMat(mat, n))
      cout << "This is Hankel Matrix";
   else
      cout << "This is not Hankel Matrix";
}

輸出

This is Hankel Matrix

更新時間: 2019-10-22

144 次瀏覽

開啟你的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.