1. 程式人生 > >給定整數N,按要求輸出Z字型矩陣

給定整數N,按要求輸出Z字型矩陣

給定整數N,按要求輸出如下Z字型矩陣(N*N):(2014-03北京某移動網際網路公司面試題)

例如:N=4

輸出:

要求:空間複雜度為O(N)

#include<iostream>
using namespace std;
void display(int N)
{  
	int*a=new int[N];//先宣告一個數組 
	memset(a,0,N*sizeof(int));
	if(N%2==0)
	{
        for(int i=1;i<=N;i++)
		{//先列印第一行  
            if(i%2==1)
			{//第一行中奇數序列的數  
                for (int j = 1; j <=i; j++) 
				{  
                    a[i-1]+=j;  
                }  
            }
			else 
			{  
                a[i-1]=a[i-2]+1;  
            }  
			
			cout<<a[i-1]<<"  ";
			
        }  
        cout<<endl;
        for(int k=2;k<=N;k++)
		{  
            if(k%2==0)
			{  
                for (int i = 1; i <=N-1; i++) 
				{  
                    if(i%2==1)
					{  
                        a[i-1]=a[i]+1;  
                    }else 
					{  
                        a[i-1]=a[i]-1;  
                    }  
                    cout<<a[i-1]<<"  ";  
                }  
				
				a[N-1]=a[N-1]+2*(N-k+1);  
				
				cout<<a[N-1];  
            }
			else
			{  
                for (i = 1; i <=N-1; i++) 
				{  
                    if(i%2==1)
					{  
                        a[i-1]=a[i]-1;  
                    }
					else 
					{  
                        a[i-1]=a[i]+1;  
                    }  
                    cout<<a[i-1]<<"  ";  
                }  
                a[N-1]=a[N-1]+1;  
                cout<<a[N-1];  
            }  
            cout<<endl;;  
        }  
	}
	else
	{
		for(int i=1;i<=N;i++)
		{//先列印第一行  
            if(i%2==1)
			{//第一行中奇數序列的數  
                for (int j = 1; j <=i; j++) 
				{  
                    a[i-1]+=j;  
                }  
            }
			else 
			{  
                a[i-1]=a[i-2]+1;  
            }  
			
			cout<<a[i-1]<<"  ";
			
        }  
        cout<<endl;
        for(int k=2;k<=N;k++)
		{  
            if(k%2==1)
			{  
                for (int i = 1; i <=N-1; i++) 
				{  
                    if(i%2==0)
					{  
                        a[i-1]=a[i]+1;  
                    }else 
					{  
                        a[i-1]=a[i]-1;  
                    }  
                    cout<<a[i-1]<<"  ";  
                }  
				
				a[N-1]=a[N-1]+2*(N-k+1);  
				
				cout<<a[N-1];  
            }
			else
			{  
                for (i = 1; i <=N-1; i++) 
				{  
                    if(i%2==0)
					{  
                        a[i-1]=a[i]-1;  
                    }
					else 
					{  
                        a[i-1]=a[i]+1;  
                    }  
                    cout<<a[i-1]<<"  ";  
                }  
                a[N-1]=a[N-1]+1;  
                cout<<a[N-1];  
            }  
            cout<<endl;;  
        }  

	}
	delete []a;
}  
int main()
{
	int n;
	cin>>n;
	display(n);	
	return 0;
}