程序员面试题精选(46):矩阵式螺旋输出

来源:互联网 发布:apache kafka有什么用 编辑:程序博客网 时间:2024/04/30 02:07

output1.JPG

题目描述:如上图式的输出矩阵。

代码如下:

#include <cstdio>


void MatrixSpiralOutput(int n)
{
    int **matrix = new int*[n]();
    for (int idx = 0; idx < n; idx++)
    {
        matrix[idx] = new int[n]();
    }

    int row = 0, col = 0;
    int i = 0;
    int len = n * n;
    int circle = 0;

    while (i < len)
    {
        for( ;row < n - circle; row++)
            matrix[row][col] = ++i;

        row--;
        col++;

        for( ; col < n - circle; col++)
            matrix[row][col] = ++i;

        row--;
        col--;

        for( ; row >= circle; row--)
            matrix[row][col] = ++i;

        row++;
        col--;

        for( ;col > circle; col--)
            matrix[row][col] = ++i;

        row++;
        col++;

        circle++;
    }

    printf("/n   The  Array matrix[%d][%d] is :", n, n);
    for(int k = 0; k < n; k++)
    {
        printf("/n/n      ");
        for(int j = 0; j < n; j++)
            printf("%-5d", matrix[k][j]);
    }
    printf("/n/n");

    for(idx = 0 ; idx < n ; idx++)
        delete [] matrix[idx];
    delete [] matrix;
 
}

int main()
{
 MatrixSpiralOutput(8);

原创粉丝点击