面试题29:顺时针打印矩阵

本体考察数组的使用。注意本体使用vector的指针形式。

C++版

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

void printMatrixInCircle(vector<vector<int>> numbers, int rows, int columns, int start, vector<int>* ans){
    int endX = columns - 1 - start;
    int endY = rows - 1 - start;

    // 从左到右打印一行
    for(int i = start; i <= endX; ++i)
    {
        int number = numbers[start][i];
        (*ans).push_back(number);
        cout<<number<<",左到右";
    }

    // 从上到下打印一列
    if(start < endY)
    {
        for(int i = start + 1; i <= endY; ++i)
        {
            int number = numbers[i][endX];
            (*ans).push_back(number);
            cout<<number<<",上到下";
        }
    }

    // 从右到左打印一行
    if(start < endX && start < endY)
    {
        for(int i = endX - 1; i >= start; --i)
        {
            int number = numbers[endY][i];
            (*ans).push_back(number);
            cout<<number<<",右到左";
        }
    }

    // 从下到上打印一行
    if(start < endX && start < endY - 1)
    {
        for(int i = endY - 1; i >= start + 1; --i)
        {
            int number = numbers[i][start];
            (*ans).push_back(number);
            cout<<number<<",下到上";
        }
    }
}

vector<int> printMatrix(vector<vector<int>> matrix){
    vector<int> ans;
    int rows = matrix.size();
    int columns = matrix[0].size();
    cout<<rows<<endl<<columns<<endl;
    int start = 0;
    while(rows > start * 2 && columns > start * 2){
        printMatrixInCircle(matrix, rows, columns, start, &ans);
        start++;
    }
    return ans;
}


int main()
{
    vector<vector<int>> v2d;
    for(int i=0;i<5;i++)
    {
        v2d.push_back(vector<int>());//不断往v2d里加行
    }
    for(int i=0;i<v2d.size();i++)//行
    {
        for(int j=0;j<5;j++)//添加5列
        {
            v2d[i].push_back(i*j);
        }
    }

    //v2d.push_back(vector<int>());
    //v2d[0].push_back(1);
    vector<int> ans = printMatrix(v2d);
    cout<<endl;
    for(int i = 0; i < ans.size(); i++){
        if(i == ans.size() - 1)
            cout<<ans[i];
        else
            cout<<ans[i]<<", ";
    }
    return 0;
}
posted @ 2020-07-27 10:47  程序员曾奈斯  阅读(88)  评论(0编辑  收藏  举报