面试题29:顺时针打印数组

思路:将整个问题划分成多个子问题,打印数组的每一圈都是一个子问题。

#include <iostream>
#include <vector>
using namespace std;

// 注意:参数类型不要用unsigned int,因为在本程序中用到了0减1,而0减1后会溢出。
void printMatClockwisely(int(*numbers)[4], int cols, int rows);
void printMatInCircle(int(*numbers)[4], int cols, int rows, int start);

void printMatClockwisely(int(*numbers)[4], int cols, int rows) {
    if (numbers == nullptr || cols <= 0 || rows <= 0) {
        return;
    }
    cout << "参数格式正确" << endl;
    for (unsigned int start = 0; start * 2 < cols && start * 2 < rows; ++start) {
        printMatInCircle(numbers, cols - (start)*2, rows - (start) * 2, start); // 子问题
    }

}

void printMatInCircle(int(*numbers)[4], int cols, int rows, int start) {
    if (numbers == nullptr || cols <= 0 || rows <= 0) {
        return;
    }

    int c = start;
    int r = start;
    int end_c = start + cols - 1;
    int end_r = start + rows - 1;
    
    while (c <= end_c) {
        cout << numbers[r][c] << endl;
        ++c;
    }
    
    if (rows >= 2) {
        c = end_c;
        ++r;
        while (r <= end_r) {
            cout << numbers[r][c] << endl;
            ++r;
        }
        
        r = end_r;

        if (cols >= 2) {
            --c;
            while (c >= start) {
                cout << numbers[r][c] << endl;
                --c;
            }
            
            if (rows >= 3) {
                c = start;
                --r;
                while (r > start) {
                    cout << numbers[r][c] << endl;
                    --r;
                }
            }
        }
        
    }
}

int main()
{
    int numbers[4][4] = {
    {1,2,3,4},
    {5,6,7,8},
    {9,10,11,12},
    {13,14,15,18}
    };
    
    printMatClockwisely(numbers, 4, 4);

    return 0;
}


参考:《剑指offer》

发布了92 篇原创文章 · 获赞 2 · 访问量 3416

猜你喜欢

转载自blog.csdn.net/zxc120389574/article/details/105120606