返回

绕矩阵一圈:刷题笔记从顺时针打印说起

前端

大家好,今天,我们一起了解算法题目:顺时针打印矩阵。这道题在一次腾讯笔试中出现过,当时,我没有写完。

01. 顺时针打印矩阵

1). 题目要求

  • 矩阵是一个二维数组。
  • 要完成顺时针打印,上-右-下-左,呈环形打印。
    -如下图所示:

手写图如下:

1  2  3  4
5  6  7  8
9  10 11 12
13 14 15 16

2). 解决方案

// 4边界分别是 上边界、右边界、下边界、左边界
// left表示左边界,top表示上边界,right表示右边界,bottom表示下边界
int PrintMatrixClockwisely(int** numbers, int rows, int columns)
{
    if(numbers == NULL || rows <= 0 || columns <= 0)
        return 0;
    int left = 0, top = 0, right = columns - 1, bottom = rows - 1;
    int* result = (int*)malloc((rows * columns) * sizeof(int));
    int index = 0;
    while(left <= right && top <= bottom)
    {
        for(int i = left; i <= right; ++i)    // 从左到右打印上边界
            result[index++] = numbers[top][i];
        for(int i = top + 1; i <= bottom; ++i)  // 从上到下打印右边界
            result[index++] = numbers[i][right];
        if(top < bottom)                      // 从右到左打印下边界
        {
            for(int i = right; i >= left; --i)
                result[index++] = numbers[bottom][i];
        }
        if(left < right)                       // 从下到上打印左边界
        {
            for(int i = bottom - 1; i > top; --i)
                result[index++] = numbers[i][left];
        }
        ++left;                                // 左边界向右移动
        ++top;                                 // 上边界向下移动
        --right;                               // 右边界向左移动
        --bottom;                             // 下边界向上移动
    }
    return *result;
}

02. 总结

这篇刷题笔记,我们以算法题目:顺时针打印矩阵为例,和大家分享了这道题的解题思路和代码实现。最后,欢迎大家在评论区留言,我们一起探讨和学习。

我们下期见!