给定一个数n,输出n的环形矩阵

#include 
#include 
#include 
using namespace std;


void HelixMatrix(int n)
{
    int **a = new int*[n];
	int i;
    for (i = 0; i < n; i++)
        a[i] = new int[n];

  int m = 0;
	int j;
	int t;

	  
	for(i = 0; i <= n/2; i++)
	{
		//向右走到n-i-1个数,j最后已到n-i;
		for(j = i; j <= n-i-1; j++)
			a[i][j] = m++;
		
		//向下走到头
		j--;
		for(t = i+1; t <= n-1-i; t++)
			a[t][j] = m++;
		//向左走
		t-=1;
		for(j-=1; j >= i; j--)
			a[t][j] = m++;
		j+=1;
		for(t-=1; t>i; t--)
			a[t][j] = m++;
	}
	

	if(n%2)
		a[n/2][n/2] = --m;
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j ++)
            cout << a[i][j] << " ";
        cout << endl;
    }
    //释放a
    for(i = 0; i < n; i++) {
        delete [] a[i];
    }
    delete []a;
}

int main(int argc, char** argv)
{
   int n;
   while(cin >> n)
		HelixMatrix(n);

}


给定一个数n,输出n的环形矩阵_第1张图片



你可能感兴趣的:(找工作常见算法)