C++經典編程題目(六)倒填數 蛇形填數 迴轉填數

6. 矩陣中填數. 當給出 N*N 的矩陣,要求用程序填入下列形式的數:
   ① 倒填,例如N=5             ② 蛇形填數              ③ 迴轉填數
#include <iostream>
#include <stdio.h>

using namespace std;

/*
本質上是一個按照規律構建二維矩陣的問題
*/

void Inversion(int n)
{
	//只有一個數的時候輸出1
	if (n == 1)
	{
		printf("1");
	}

	//動態生成一個二維數組
	int **shouList = new int*[n];//開闢行
	for (int i = 0; i < n; i++)
		shouList[i] = new int[n]; //開闢列

	int max = n*n;

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			shouList[i][j] = max;
			max--;
		}
	}

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			printf("%4d", shouList[i][j]);
		}
		printf("\n");
	}
	printf("\n");
}

void Snake(int n)
{
	//只有一個數的時候輸出1
	if (n == 1)
	{
		printf("1");
	}

	//動態生成一個二維數組
	int **shouList = new int*[n];//開闢行
	for (int i = 0; i < n; i++)
		shouList[i] = new int[n]; //開闢列

	int row = 0, col = 0;
	int Filler = 1;
	int loop = 0;

	for (size_t loop = 0; loop < 2*n-1; loop++)
	{
		row = (loop < n) ? 0 : loop - (n - 1);
		col = (loop < n) ? loop : (n - 1);
		for (int j = row; j <= col; j++)
			(loop % 2) ? (shouList[j][loop - j] = Filler++) : (shouList[loop - j][j] = Filler++);
	}

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			printf("%4d", shouList[i][j]);
		}
		printf("\n");
	}
	printf("\n");
}

void Rotation(int n)
{
	//只有一個數的時候輸出1
	if (n == 1)
	{
		printf("1");
	}

	//動態生成一個二維數組
	int **shouList = new int*[n];//開闢行
	for (int i = 0; i < n; i++)
		shouList[i] = new int[n]; //開闢列

	int Filler = 1;
	int head = 0, tail = n-1;
	int row = 0, col = 0;

	for (int i = 0; i <= n / 2; i++)
	{

		if (head == tail)
		{
			shouList[head][tail] = Filler;
		}
		for (row = head; row < tail; row++)
		{
			shouList[row][col] = Filler++;
		}
		for (col = head; col < tail; col++)
		{
			shouList[row][col] = Filler++;
		}
		for (row = tail; row > head; row--)
		{
			shouList[row][col] = Filler++;
		}
		for (col = tail; col> head; col--)
		{
			shouList[row][col] = Filler++;
		}
		head++; 
		tail--;
		row = head;
		col = head;
	}

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			printf("%4d", shouList[i][j]);
		}
		printf("\n");
	}
	printf("\n");
}

int main()
{
	int n = 0,choose = 0;

	cout << "Please input the dimension you want to Constructing the Matrix :" << endl;
	cin >> n;
	cout << "Please choose the Matrix:" << endl;
	cout << "1. Inversion ;" << endl;
	cout << "2. Snake ;" << endl;
	cout << "3. Rotation ;" << endl;
	cin >> choose;

	switch (choose)
	{
	case 1:
		Inversion(n);
		break;
	case 2:
		Snake(n);
		break;
	case 3:
		Rotation(n);
		break;
	default:
		cout << "Error!" << endl;
		break;
	}

	system("pause");
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章