题目描述:输入一个N,求一个N*N矩阵,规定矩阵沿45度线递增,形成一个zigzag数组(JPEG编码里取像素数据的排列顺序),请问如何用C++实现?
#include <iostream> using namespace std; int main() { //建立矩阵 int N; cout<<"请输入矩阵的宽度:"; cin>>N; cout<<endl; int **a=new int*[N]; for(int i=0;i<N;i++) a[i]=new int[N]; //之字存储数据 int num = 0; int m = 0; while(m!=N) { int j=m; if(m%2) { for(int i=0;i<=m;i++) { a[i][j]=num++; j--; } } else { for(int i=0;i<=m;i++) { a[j][i]=num++; j--; } } m++; } int n=N; for(int count=1;count<=N-1;count++) { int j=N-1; if(n%2) { for(int i=count;i!=N;i++) { a[i][j]=num++; j--; } n++; } else { for(int i=count;i!=N;i++) { a[j][i]=num++; j--; } n++; } } //打印数据 for(int i=0;i!=N;i++) { for(int j=0;j!=N;j++) { cout<<a[i][j]<<" "; } cout<<endl; } return 0; }
DEV测试结果:
- 2016.5.4 修改
#include <iostream> using namespace std; int main() { //建立矩阵 int N; cout << "请输入矩阵的宽度:"; cin >> N; cout << endl; int **a = new int*[N]; for (int i = 0; i<N; i++) a[i] = new int[N]; //之字存储数据 int num = 0; int m = 0; while ( m != 2 * N - 1 ) { if ( 1 == m % 2 && m <= N-1) //右上到左下 { for (int i = 0 ,j = m; i <= m; ) { a[i][j] = num++; j--; i++; } } if (0 == m % 2 && m <= N - 1) //左下到右上 { for (int j = 0 ,i = m; j <= m; ) { a[i][j] = num++; i--; j++; } } if (1 == m % 2 && m > N - 1) //右上到左下 { for (int i = m - N + 1, j = N - 1; i != N;) { a[i][j] = num++; i++; j--; } } if (0 == m % 2 && m > N - 1) //左下到右上 { for (int i = N - 1, j = m - N + 1; j != N;) { a[i][j] = num++; j++; i--; } } m++; } //打印数据 for (int i = 0; i != N; i++) { for (int j = 0; j != N; j++) { cout << a[i][j] << " "; } cout << endl; } return 0; }
题目出处:《程序员面试宝典》