ในเมทริกซ์ที่กำหนด เมื่อองค์ประกอบส่วนใหญ่เป็นศูนย์ เราเรียกมันว่าเมทริกซ์เบาบาง ตัวอย่าง − เมทริกซ์ 3 x3
1 1 0 0 0 2 0 0 0
ในเมทริกซ์นี้ อิลิเมนต์ส่วนใหญ่เป็นศูนย์ จึงเป็นเมทริกซ์แบบกระจาย
ปัญหา
ตรวจสอบว่าเมทริกซ์เป็นเมทริกซ์เบาบางหรือไม่
วิธีแก้ปัญหา
-
ให้เราถือว่า ZERO ในเมทริกซ์มากกว่า (แถว * คอลัมน์)/2
-
จากนั้น เมทริกซ์จะเป็นเมทริกซ์เบาบาง ไม่เช่นนั้นก็ไม่ใช่
โปรแกรม
ต่อไปนี้เป็นโปรแกรมตรวจสอบว่าเมทริกซ์ที่ให้มานั้นเป็นเมทริกซ์เบาบางหรือไม่ -
#include<stdio.h>
#include<stdlib.h>
int main(){
int row,col,i,j,a[10][10],count = 0;
printf("Enter row\n");
scanf("%d",&row);
printf("Enter Column\n");
scanf("%d",&col);
printf("Enter Element of Matrix1\n");
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
scanf("%d",&a[i][j]);
}
}
printf("Elements are:\n");
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
/*checking sparse of matrix*/
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
if(a[i][j] == 0)
count++;
}
}
if(count > ((row * col)/2))
printf("Matrix is a sparse matrix \n");
else
printf("Matrix is not sparse matrix\n");
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Run 1: Enter row 3 Enter Column 2 Enter Element of Matrix1 1 0 2 0 2 0 Elements are: 1 0 2 0 2 0 Matrix is not sparse matrix Run 2: Enter row 3 Enter Column 2 Enter Element of Matrix1 1 0 0 0 0 0 Elements are: 1 0 0 0 0 0 Matrix is a sparse matrix