在C ++中检查矩阵是否为二进制矩阵的程序

二进制矩阵是所有元素都是二进制值(即0或1)的矩阵。二进制矩阵也可以称为布尔矩阵,关系矩阵,逻辑矩阵

在下面的示例中给出           

$$\ begin {bmatrix} 0&1&0
\\ 1&1&0
\\ 1&0&1
\\ \ end {bmatrix} \:\:\:\:\:\:\:\:\:\ :
\ begin {bmatrix}
0&3&0
\\ 1&1&0
\\ 1&0&2
\\ \ end {bmatrix} \\\ tiny This \:is \:a \:Binary \:Matrix \ :\:\:\:\:\:\:\:
This \:is \:not \:a \:binary \:matrix $$

在上图中,左边的第一个矩阵是二进制矩阵,其他矩阵中有一些不是Binary(0或1)的值以红色突出显示,即3和2,因此不是二进制矩阵。

示例

Input: m[4][3] = { { 0, 0, 0, 0 },
   { 1, 1, 1, 1 },
   { 1, 1, 0, 0 } }
Output: its a binary matrix

方法

我们可以遍历整个矩阵并检查所有元素是否为0或1,然后将其打印为二进制矩阵,否则将其打印为非二进制矩阵。

算法

Start
Step 1 -> define macros as #define row 3 and #define col 4
Step 2 -> Declare function to 检查矩阵是否为二进制矩阵
   bool check(int arr[][col])
      Loop For int i = 0 and i < row and i++
         Loop For int j = 0 and j < col and j++
            IF(!(arr[i][j] = 0 || arr[i][j] = 1))
               return false
            End
         End
   End
   return true
step 3 -> In main()   Declare an array as int arr[row][col] = { { 0, 0, 0, 0 },
      { 1, 1, 1, 1 },
      { 1, 1, 0, 0 } }
   If (check(arr))
      Print its a binary matrix
   Else
      Print its not a binary matrix
Stop

示例

#include <bits/stdc++.h>
using namespace std;
#define row 3
#define col 4
//检查矩阵是否为二进制矩阵
bool check(int arr[][col]){
   for (int i = 0; i < row; i++){
      for (int j = 0; j < col; j++){
         if (!(arr[i][j] == 0 || arr[i][j] == 1))
            return false;
      }
   }
   return true;
}
int main(){
   int arr[row][col] = { { 0, 0, 0, 0 },
      { 1, 1, 1, 1 },
      { 1, 1, 0, 0 } };
   if (check(arr))
      cout << "its a binary matrix";
   else
      cout << "its not a binary matrix";
   return 0;
}

输出结果

its a binary matrix