Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรมตรวจสอบว่าเมทริกซ์เป็น Binary Matrix หรือไม่ใน C++


Binary Matrix คือเมทริกซ์ที่ทุกองค์ประกอบเป็นค่า binary คือ 0 หรือ 1 Binary Matrix เรียกอีกอย่างว่า Boolean matrix, Relational Matrix, Logical matrix

ตัวอย่าง −

$$\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 Matrix เมทริกซ์ขวา มีค่า 3 และ 2 ที่ไม่ใช่ 0 หรือ 1 จึงไม่ใช่ Binary Matrix

ตัวอย่าง

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

วิธีแก้

วนลูปเมทริกซ์ทั้งหมด ตรวจสอบทุกองค์ประกอบ หากเป็น 0 หรือ 1 ทั้งหมด พิมพ์ว่าเป็น Binary Matrix ไม่ใช่พิมพ์ว่าไม่ใช่

อัลกอริทึม

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