以奇怪的顺序显示矩阵元素

Displaying Matrix elements in Strange Order

本文关键字:元素 显示 顺序      更新时间:2023-10-16

我不太清楚这种印刷顺序叫什么,所以我觉得很奇怪。

考虑以下示例示例:

1 3 5
2 6 7
预期输出:

1,2
1,6
1,7
3,2
3,6
3,7
5,2
5,6
5,7

或者这个例子:

1 2 3
4 5 6
7 8 9
输出:

1,4,7
1,4,8
1,4,9
1,5,7
1,5,8
1,5,9 
... and so on.

我已经分析过,对于任何给定的矩阵,可能的组合数将是rows^columns。下面是我的解决方案:

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <cstdio>
using namespace std;
void printAllPossibleCombinations(int** a, int h, int n, string prefix)
{
    if (h == 0)
    {
        for (int i = 0; i < n; i++)
        {
            cout << prefix << a[0][i] << endl;
        }
    }
    else
    {
        for (int i = 0; i < n; i++)
        {
            string recursiveString = prefix;
            recursiveString.append(to_string(a[h][i]));
            recursiveString.append(1, ',');
            printAllPossibleCombinations(a, h-1, n, recursiveString);
        }
    }
}
int main()
{
    int **a;
    int m,n,k;
    cout<<"Enter number of rows: ";
    cin>>m;
    a = new int*[m];
    cout<<endl<<"Enter number of columns: ";
    cin>>n;
    for(int i=0;i<m;i++)
    {
        a[i] = new int [n];
    }
    for(int i=0;i<m;i++)
    {
        for(int j = 0; j < n;j++)
        {
            cout<<"Enter a[" << i << "][" << j<< "] = ";
            cin>>a[i][j];
            cout<<endl;
        }
    }
    printAllPossibleCombinations(a, m-1, n, "");
    return 0;
}

是否有一种更简单、更优化的方法来做这件事?请建议。

谢谢

正如你所说,在算法中有rows^columns的东西需要物理打印,所以你不能比O(rows^columns)算法做得更好,你的算法是最优的,因为你会得到

相关文章: