# C++ code to check given matrix is good or not

C++Server Side ProgrammingProgramming

Suppose we have one n x n matrix. The matrix is said to be a good matrix where every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. We have to check whether given matrix is good or not.

So, if the input is like

 1 1 2 2 3 1 6 4 1

Then the output will be True, because the 6 in the bottom left corner is valid because when the sum of the 2 above it and the 4 on the right. The same holds for every number not equal to 1 in this matrix.

## Steps

To solve this, we will follow these steps −

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

## Example

Let us see the following implementation to get better understanding −

#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;
}

## Input

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

## Output

1