Given a matrix with most of its elements as 0, convert this matrix to sparse matrix in C++
Input: Matrix: 0 1 0 0 0 0 2 0 0 3 0 0 0 0 5 0 0 0 0 4 Output: Sparse Matrix: 0 1 1 1 2 2 2 1 3 3 2 5 4 3 4 Explanation: Here the Sparse matrix is represented in the form Row Column Value Hence the row 0 1 1 means that the value of the matrix at row 0 and column 1 is 1
- Get the matrix with most of its elements as 0.
- Create a new 2D array to store the Sparse Matrix of only 3 columns (Row, Column, Value).
- Iterate through the Matrix, and check if an element is non zero. In this case insert this element into the Sparse Matrix.
- After each insertion, increment the value of variable length(here ‘len’). This will serve as the row dimension of the Sparse Matrix
- Print the Dimension of the Sparse Matrix and its elements.
Matrix: 0 1 0 0 0 0 2 0 0 3 0 0 0 0 5 0 0 0 0 4 Dimension of Sparse Matrix: 5 x 3 Sparse Matrix: Row Column Value 0 1 1 1 2 2 2 1 3 3 2 5 4 3 4
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sparse Matrix and its representations | Set 1 (Using Arrays and Linked Lists)
- Sparse Matrix and its representations | Set 2 (Using List of Lists and Dictionary of keys)
- Check if a given matrix is sparse or not
- Sparse Matrix Representations | Set 3 ( CSR )
- Program to convert given Matrix to a Diagonal Matrix
- Minimum number of steps to convert a given matrix into Upper Hessenberg matrix
- Minimum steps required to convert the matrix into lower hessenberg matrix
- Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix
- Convert given Matrix into sorted Spiral Matrix
- Minimize count of adjacent row swaps to convert given Matrix to a Lower Triangular Matrix
- Program to convert the diagonal elements of the matrix to 0
- Program to check diagonal matrix and scalar matrix
- Program to check if a matrix is Binary matrix or not
- In-place convert matrix in specific order
- Convert a String into a square matrix grid of characters
- Minimum steps required to convert X to Y where a binary matrix represents the possible conversions
- Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths
- Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths | Set 2
- Minimum steps to convert all top left to bottom right paths in Matrix as palindrome | Set 2
- Minimize cost to convert a given matrix to another by flipping columns and reordering rows
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.