File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ // C++ program for Sparse Matrix Representation
2
+ // using Array
3
+ #include < stdio.h>
4
+
5
+ int main ()
6
+ {
7
+ // Assume 4x5 sparse matrix
8
+ int sparseMatrix[4 ][5 ] =
9
+ {
10
+ {0 , 0 , 3 , 0 , 4 },
11
+ {0 , 0 , 5 , 7 , 0 },
12
+ {0 , 0 , 0 , 0 , 0 },
13
+ {0 , 2 , 6 , 0 , 0 }
14
+ };
15
+
16
+ int size = 0 ;
17
+ for (int i = 0 ; i < 4 ; i++)
18
+ for (int j = 0 ; j < 5 ; j++)
19
+ if (sparseMatrix[i][j] != 0 )
20
+ size++;
21
+
22
+ // number of columns in compactMatrix (size) must be
23
+ // equal to number of non - zero elements in
24
+ // sparseMatrix
25
+ int compactMatrix[3 ][size];
26
+
27
+ // Making of new matrix
28
+ int k = 0 ;
29
+ for (int i = 0 ; i < 4 ; i++)
30
+ for (int j = 0 ; j < 5 ; j++)
31
+ if (sparseMatrix[i][j] != 0 )
32
+ {
33
+ compactMatrix[0 ][k] = i;
34
+ compactMatrix[1 ][k] = j;
35
+ compactMatrix[2 ][k] = sparseMatrix[i][j];
36
+ k++;
37
+ }
38
+
39
+ for (int i=0 ; i<3 ; i++)
40
+ {
41
+ for (int j=0 ; j<size; j++)
42
+ printf (" %d " , compactMatrix[i][j]);
43
+
44
+ printf (" \n " );
45
+ }
46
+ return 0 ;
47
+ }
You can’t perform that action at this time.
0 commit comments