求Zigzag数组

本文介绍了一种特殊的矩阵遍历方式——Zigzag遍历,并提供了一个C++实现的例子。该算法将N*N矩阵沿45度方向进行遍历,形成一个递增的Zigzag数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

面试题:输入N,求一个N*N矩阵,规定矩阵沿45度线递增,形成一个zigzag数组。

#include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;

void CreateZigzag(int *zigzag,int **data,int n)		//data数组是N*N的数组,其中数据需要以Zigzag存入数组,所以zigzag的数组长度为N*N
{
	//int **data,如果需要访问二维数组的数据*((int*)data + n*i + j) 等价data[i][j]
	int step = n + n - 1;
	int i,j;
	int datano = 0;
	int startnum = 0;
	int count = 1;
	bool triangle = true;			//记录是否在上半三角还是下半三角
	while(step > 0)
	{
		if(count == n)
			triangle = false;
		j = startnum;
		for(i = 0; i < count;i++)
		{
			if(triangle)
			{
				zigzag[i * n + j] = *((int*)data + datano);
				j = (j + n - 1) % n;
			}
			else
			{
				zigzag[(n - count + i) * n + j] = *((int*)data + datano);
				j = (j + n - 1) % n;
			}
			datano++;
		}
		if(triangle)
		{
			count++;
			startnum++;
		}
		else
			count--;
		step--;
	}

}

void Output(int *data,int length)
{
	cout<<"The result of zigzag is : "<<endl;
	int n = sqrt(double(length));
	for(int i = 0;i < length;i++)
	{
		if(i % n == 0)
			cout<<endl;
		cout<<setw(6)<<data[i];
	}
	cout<<endl;
}

int main()
{
	int data[][8] = {0,1,2,3,4,5,6,7,8,9,10,
		11,12,13,14,15,16,17,18,19,20,
		21,22,23,24,25,26,27,28,29,30,
		31,32,33,34,35,36,37,38,39,40,
		41,42,43,44,45,46,47,48,49,50,
		51,52,53,54,55,56,57,58,59,60,61,62,63,64};
	int zigzag[64];

	CreateZigzag(zigzag,(int**)data,8);
	Output(zigzag,64);
	return 0;
}
The result of zigzag is :

     0     1     3     6    10    15    21    28
     2     4     7    11    16    22    29    36
     5     8    12    17    23    30    37    43
     9    13    18    24    31    38    44    49
    14    19    25    32    39    45    50    54
    20    26    33    40    46    51    55    58
    27    34    41    47    52    56    59    61
    35    42    48    53    57    60    62    63
请按任意键继续. . .



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值