每日一练2020/7/31(C++)———顺时针打印矩阵

顺时针打印矩阵
题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

#include 
using namespace std;

void print(int number)
{
    cout << number << " ";
}

void Print_Circle(int** numbers, int rows, int columns, int start)
{
    int end_row = rows - start - 1;
    int end_column = columns - start - 1;
    for (int i = start; i <= end_column; i++)// 从左到右打印一行
        print(numbers[start][i]);
    if (start >= end_row)
        return;
    for (int i = start + 1; i <= end_row; i++)// 从上到下打印一列
        print(numbers[i][end_column]);
    if (start >= end_column)
        return;
    for (int i = end_column - 1; i >= start; i--)// 从右到左打印一行
        print(numbers[end_row][i]);
    for (int i = end_row - 1; i > start; i--)// 从下到上打印一列
        print(numbers[i][start]);
}

void Print_Clockwise(int** numbers, int rows, int columns)
{
    if (numbers == NULL || columns <= 0 || rows <= 0)
    {
        return;
    }

    int start = 0;
    while (columns > 2 * start && rows > 2 * start)
    {
        Print_Circle(numbers,  rows, columns, start);
        ++start;
    }
}

/**********************************************/

void Test(int rows, int columns)
{
    cout << endl;
	int** numbers = new int* [rows];
	for (int i = 0; i < rows; i++)
	{
		numbers[i] = new int[columns];
		for (int j = 0; j < columns; j++)
		{
			numbers[i][j] = i * columns + j + 1;
		}
	}
    cout << "matrix:" << endl;
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            cout << numbers[i][j] << " ";
        }
        cout << endl;
    }
    cout << "results:" << endl;
	Print_Clockwise(numbers, rows, columns);
	cout << endl;


    for (int i = 0; i < rows; ++i)
        delete[](int*)numbers[i];
	delete[] numbers;
}

测试

int main()
{   
    Test(1, 1);
    Test(2, 2);
    Test(4, 4);
    Test(5, 5);
    Test(1, 5);
    Test(2, 5);
    Test(3, 5);
    Test(4, 5);
    Test(5, 1);
    Test(5, 2);
    Test(5, 3);
    Test(5, 4);

    return 0;
}

结果:
每日一练2020/7/31(C++)———顺时针打印矩阵_第1张图片

你可能感兴趣的:(每日一练,c++)