📜  C ++程序将矩阵转换为稀疏矩阵

📅  最后修改于: 2021-05-31 19:30:52             🧑  作者: Mango

给定一个矩阵,其大多数元素为0,请在C++中将该矩阵转换为稀疏矩阵
例子:

Input: Matrix:
0 1 1
1 2 2
2 1 3
3 2 5
4 3 4
Output: Sparse Matrix: 
0 1 0 0 
0 0 2 0 
0 3 0 0 
0 0 5 0 
0 0 0 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

方法:

  1. 获取其大多数元素为0的矩阵。
  2. 创建一个新的2D数组以存储仅3列(行,列,值)的稀疏矩阵。
  3. 遍历Matrix,并检查元素是否为非零。在这种情况下,将此元素插入稀疏矩阵。
  4. 每次插入后,增加可变长度的值(此处为“ len”)。这将用作稀疏矩阵的行维
  5. 打印稀疏矩阵及其元素的尺寸。
CPP
// C++ program to convert a Matrix
// into Sparse Matrix
 
#include 
using namespace std;
 
// Maximum number of elements in matrix
#define MAX 100
 
// Array representation
// of sparse matrix
//[][0] represents row
//[][1] represents col
//[][2] represents value
int data[MAX][3];
 
// total number of elements in matrix
int len;
 
// insert elements into sparse matrix
void insert(int r, int c, int val)
{
    // insert row value
    data[len][0] = r;
 
    // insert col value
    data[len][1] = c;
 
    // insert element's value
    data[len][2] = val;
 
    // increment number of data in matrix
    len++;
}
 
// printing Sparse Matrix
void print()
{
    cout << "\nDimension of Sparse Matrix: "
         << len << " x " << 3;
    cout << "\nSparse Matrix: \nRow Column Value\n";
 
    for (int i = 0; i < len; i++) {
 
        cout << data[i][0] << " "
             << data[i][1] << " "
             << data[i][2] << "\n";
    }
}
 
// Driver code
int main()
{
    int i, j;
    int r = 5, c = 4;
 
    // Get the matrix
    int a[r] = { { 0, 1, 0, 0 },
                    { 0, 0, 2, 0 },
                    { 0, 3, 0, 0 },
                    { 0, 0, 5, 0 },
                    { 0, 0, 0, 4 } };
 
    // print the matrix
    cout << "\nMatrix:\n";
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            cout << a[i][j] << " ";
        }
        cout << endl;
    }
 
    // iterate through the matrix and
    // insert every non zero elements
    // in the Sparse Matrix
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            if (a[i][j] > 0)
                insert(i, j, a[i][j]);
 
    // Print the Sparse Matrix
    print();
 
    return 0;
}


输出:
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
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”