蛇形矩阵

思想:从外到内每次打印一个正方形

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


int main()
{
	int n,i,j;
	cin >> n;
	int k;
	int	s=1;
	int **m;
	//m = (int **)malloc(n*sizeof(int*));//c二维数组动态分配内存
	//for (k = 0; k < n; k++)
	//{
	//	m[k] = (int*)malloc(n*sizeof(int));
	//	memset(m[k], 0, n*sizeof(int));
	//}

	m = new int*[n];//c++二维数组动态分配内存
	for (k = 0; k < n; k++)
	{
		m[k] = new int[10];
		memset(m[k], 0, n*sizeof(int));//初始化为0
	}
	

	i = j = 0;

	for (k = n; k >= 1; k=k-2)//从外到内每次赋值一个正方形
	{
		for (int a = 1; a <= k; a++)//第一条边:从左到右
		{			
			m[i][j] = s;
			j++;
			s++;
		}
		j--;
		i++;
		for (int b = 1; b <= k-1; b++)//第二条边:从上到下
		{
			m[i][j] = s;
			s++;
			i++;
		}
		i--;
		j--;
		for (int c = 1; c <= k-1; c++)//第三条边:从右到左
		{
			m[i][j] = s;
			s++;
			j--;
		}
		j++;
		i--;
		for (int d = 1; d <=k-2; d++)//第四条边:从下到上
		{
			m[i][j] = s;
			s++;
			i--;
		}
		i++;
		j++;

	}
	for (i = 0; i < n; i++)//打印矩阵
	{
		for (j = 0; j < n; j++)
			cout << m[i][j] << " ";
		cout << endl;
	}
	//for (k = 0; k < n; k++)//c释放内存
	//{
	//	free(m[k]);
	//}
	//free(m);
	for (k = 0; k < n; k++)//c++释放内存
	{
		delete[] m[k];
	}
	delete[] m;

	system("pause");
	return 0;

}


运行结果:

蛇形矩阵_第1张图片

你可能感兴趣的:(蛇形矩阵)