⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.cpp

📁 我做的一些C语言练习题,里面一共有76道题目,主要用到一些计算机常用的算法,如:递归,分治,动态规划,回溯法,AO算法等,除此之外还用到比较多的数学知识,我做了一部分,还有一些暂时还没做出来,大家也帮
💻 CPP
字号:
/************************************************************************
6. 矩阵中填数. 当给出 N*N 的矩阵,要求用程序填入下列形式的数:

   ① 倒填,例如N=5             ② 蛇形填数              ③ 回转填数

 ┌─┬─┬─┬─┬─┐   ┌─┬─┬─┬─┬─┐   ┌─┬─┬─┬─┬─┐
 │25│24│23│22│21│   │ 1│ 3│ 4│10│11│   │ 1│16│15│14│13│
 ├─┼─┼─┼─┼─┤   ├─┼─┼─┼─┼─┤   ├─┼─┼─┼─┼─┤
 │20│19│18│17│16│   │ 2│ 5│ 9│12│19│   │ 2│17│24│23│12│
 ├─┼─┼─┼─┼─┤   ├─┼─┼─┼─┼─┤   ├─┼─┼─┼─┼─┤
 │15│14│13│12│11│   │ 6│ 8│13│18│20│   │ 3│18│25│22│11│
 ├─┼─┼─┼─┼─┤   ├─┼─┼─┼─┼─┤   ├─┼─┼─┼─┼─┤
 │10│ 9│ 8│ 7│ 6│   │ 7│14│17│21│24│   │ 4│19│20│21│10│
 ├─┼─┼─┼─┼─┤   ├─┼─┼─┼─┼─┤   ├─┼─┼─┼─┼─┤
 │ 5│ 4│ 3│ 2│ 1│   │15│16│22│23│25│   │ 5│ 6│ 7│ 8│ 9│
 └─┴─┴─┴─┴─┘   └─┴─┴─┴─┴─┘   └─┴─┴─┴─┴─┘
  ***********************************************************************/

#include <stdio.h>

//打印
void output(int** array, int n)
{
	int row,col;
	for(row=0; row<n; row++)
	{
		for(col=0; col<n; col++)
		{
			printf("%4d",*((int*)array + n*row + col));
		}
		printf("\n");
	}
}

//倒填
void O_Fill(int** array, int n)
{
	int row,col;
	int counter = 1;
	for(row=n-1; row>=0; row--)
		for(col=n-1; col>=0; col--)
		{
			*((int*)array + n*row + col) = counter++; 
		}
}

//蛇形
void S_Fill(int** array, int n)
{
	bool direct=false;
	int row,col;
	int counter = 1;
	int n2 = n*n;
	row = 0; col = 0;
	*((int*)array + n*row + col) = counter;
	for(++counter; counter<=n2; counter++)
	{
		if(!direct)
		{
			row++;
			col--;
			if(row==n)
			{
				row--;
				col+=2;
				direct = !direct;
			}
			else if(col<0)
			{
				col++;
				direct = !direct;
			}
		}
		else
		{
			row--;
			col++;
			if(col==n)
			{
				row+=2;
				col--;
				direct = !direct;
			}
			else if(row<0)
			{
				row++;
				direct = !direct;
			}
		}
		*((int*)array + n*row + col) = counter;
	}

}

//回形
void H_Fill(int** array, int n)
{
	int row,col;
	int counter;
	int n2 = n*n;
	bool direct = false;

	row = 0, col = 0;
	counter = 1;
	*((int*)array + n*row + col) = counter;

	for(++counter; counter<=n2; counter++)
	{
		if(!direct)
		{
			row++;
			if(row==n)
			{
				row--;
				col++;
				direct = !direct;
			}
		}
		else
		{
			row--;
			if(row<0)
			{
				row++;
				col++;
				direct = !direct;
			}
		}
		*((int*)array + n*row + col) = counter; 
	}
	
}

void main()
{
	int array[6][6];
	O_Fill((int**)array,6);
	output((int**)array,6);


	printf("\n");

	S_Fill((int**)array,6);
	output((int**)array,6);

	printf("\n");

	H_Fill((int**)array,6);
	output((int**)array,6);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -