求Zigzag數組

面試題:輸入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
請按任意鍵繼續. . .



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