檢查矩陣是否為二值矩陣的 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