Skip to content

Commit 22b00a3

Browse files
authored
Merge pull request #478 from Spidy-Coder/Spidy-Coder-patch-1
Added Sparse matrix problem solution in DSA
2 parents 1c2df83 + cb8b224 commit 22b00a3

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Sparse Matrix/sparse matrix.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
}

0 commit comments

Comments
 (0)