C++ 程式碼,用於檢查給定的矩陣是否良好
假設我們有一個 n x n 矩陣。當矩陣中每個不等於 1 的數都可以表示為同一行中的某個數與同一列中的某個數的和時,稱該矩陣為良好矩陣。我們需要檢查給定的矩陣是否良好。
因此,如果輸入如下
| 1 | 1 | 2 |
| 2 | 3 | 1 |
| 6 | 4 | 1 |
那麼輸出將為 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP