C++ 代码,用于检查给定的矩阵是否良好


假设我们有一个 n x n 矩阵。当矩阵中每个不等于 1 的数都可以表示为同一行中的某个数与同一列中的某个数的和时,称该矩阵为良好矩阵。我们需要检查给定的矩阵是否良好。

因此,如果输入如下

112
231
641

那么输出将为 True,因为左下角的 6 是有效的,因为当其上方的 2 与右方的 4 相加时。该矩阵中每个不等于 1 的数都是如此。

步骤

为了解决这个问题,我们将遵循以下步骤 −

n := size of M
for initialize i := 0, when i < n, update (increase i by 1), do:
   for initialize j := 0, when j < n, update (increase j by 1), do:
      ok := 0
      if M[i, j] is not equal to 1, then:
         c := M[i, j]
      for initialize h := 0, when h < n, update (increase h by 1), do:
         for initialize k := 0, when k < n, update (increase k by 1), do:
            if c is same as M[i, h] + M[k, j], then:
               ok := 1
      if ok is same as 0 and M[i, j] is not equal to 1, then:
         return false
return true

示例

让我们看看以下实现以获得更好的理解 −

#include <bits/stdc++.h>
using namespace std;
bool solve(vector<vector<int>> M){
   int n = M.size();
   int c;
   bool ok;
   for (int i = 0; i < n; i++){
      for (int j = 0; j < n; j++){
         ok = 0;
         if (M[i][j] != 1)
            c = M[i][j];
         for (int h = 0; h < n; h++){
            for (int k = 0; k < n; k++)
               if (c == M[i][h] + M[k][j])
                  ok = 1;
         }
         if (ok == 0 && M[i][j] != 1){
            return false;
         }
      }
   }
   return true;
}
int main(){
   vector<vector<int>> matrix = { { 1, 1, 2 }, { 2, 3, 1 }, { 6, 4, 1 } };
   cout << solve(matrix) << endl;
}

输入

{ { 1, 1, 2 }, { 2, 3, 1 }, { 6, 4, 1 } }

输出

1

更新于: 30-Mar-2022

191 次浏览

开启你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.