检查矩阵是否为二值矩阵的 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 这是一个二值矩阵\:\:\:\:\:\:\
这是一个非二值矩阵$$
在上图中,左边的第一个矩阵是二值矩阵,另一个矩阵中一些值不是二进制(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 check if a matrix is binary matrix or not
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
//check if a matrix is binary matrix or not
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP