程序员面试题精选100题(51)-顺时针打印矩阵[算法]

面试题 时间:2019-09-22 手机网站
                                  int startX, int startY)

{

        int endX = columns - 1 - startX;

        int endY = rows - 1 - startY;

 

        PrintARowIncreasingly(numbers, columns, rows, startY, startX, endX);

 

        if(startY < endY)

                PrintAColumnIncreasingly(numbers, columns, rows, endX, startY + 1, endY);

 

        if(startX < endX && startY < endY)

                PrintARowDecreasingly(numbers, columns, rows, endY, endX - 1, startX);

 

        if(startX < endX && startY < endY - 1)

                PrintAColumnDecreasingly(numbers, columns, rows, startX, endY - 1, startY + 1);

}

接下来我们考虑如何打印一行或者一列。这对我们来说不是一件很难的事情。以函数PrintARowIncreasingly为例,我们只需要一个循环,把行号为startY,列号从startXendX的所有数字依次从数组中取出来并逐个打印就行了,对应的代码是:

void PrintARowIncreasingly(int** numbers, int columns, int rows,

                                int y, int firstX, int lastX)

{

        for(int i = firstX; i <= lastX; ++i)

        {

                int number = *(*(numbers + y) + i);

        printf("%d\t", number);