矩阵顺时针打印

#include <iostream>
#define R 3
#define C 6

void SprialPrint(int m, int n, int a[R][C])
{
    int l = 0; //starting column index
    int k = 0; //starting row index
    int i = 0;
    
    while (l < n && k < m)
    {
        for (i = l; i < n; i++)
            std::cout << a[k][i] << " ";
        k++;
    
        for (i = k; i < m; i++)
            std::cout << a[i][n - 1] << " ";
        n--;
    
        if (k < m)
        {
            for (i = n - 1; i >= l; i--)
                std::cout << a[m - 1][i] << " ";
            m--;
        }

        if (l < n)
        {
            for (i = m - 1; i >= k; i--)
                std::cout << a[i][l] << " ";
            l++;
        }
    }
    

};

int main()
{
    int a[R][C] = { {1,  2,  3,  4,  5,  6},
                    {7,  8,  9,  10, 11, 12},
                    {13, 14, 15, 16, 17, 18}
    };

    SprialPrint(R, C, a);
    return 0;
};

你可能感兴趣的:(矩阵顺时针打印)