画螺旋矩阵

提交数: 58, 通过率: 62.07%, 平均分: 66.38

题目描述:

螺旋矩阵是指一个呈螺旋状的矩阵,他的数字由第一行开始到右边不断变大,向下变大,向左变大,向上变大,如此循环。例如5*5的矩阵数字排列规律如图:

1658196044740601371.png

输入格式:

输入一个数n。

输出格式:

画出对应的n*n的螺旋矩阵。

数据范围:

n<=10

样例输入:

5

样例输出:

[1, 2, 3, 4, 5]
[16, 17, 18, 19, 6]
[15, 24, 25, 20, 7]
[14, 23, 22, 21, 8]
[13, 12, 11, 10, 9]

提示:

请完善下列程序:

#include <bits/stdc++.h>
using namespace std;
#define LL long long
int arr[20][20],n;

void func( int x, int y ,int num ,int n){
	if ( n<=0 ) return ;
	if ( n == 1 ){
		arr[x][y] = ________(1)________ ;
		return ;
	}
	for ( int i =0; i<n; i++ ){     //向右输出数字
        _________(2)_________
        num+=1;
    }
    for ( int i=0; i<n-1; i++ ){    //向下输出数字
        arr[x+1+i] [y+n-1] =num;
        num += 1;
    }
    for ( int i=0; i<n-1; i++ ){    //向左输出数字
        arr[x+n-1] [y+n-2-i] =num;
        num+=1;
    }
    for ( int i=0; i<n-2; i++ ){    //向上输出数字
        arr[x+n-2-i][y] = num;
        num += 1;
    }
    func(  __________(3)__________  );
}

int main(){
	cin >> n;
	func( 1,  1, 1, n );   // [x,y], 从1开始生成, 矩阵的初始规模为n
	for (int i=1; i<= n; i++){
		cout <<"["<<arr[i][1];
		for ( int j=2; j<=n; j++)
			cout << ", "<<arr[i][j];
		cout << "]\n";
	}
	return 0;
}
时间限制: 1000ms
空间限制: 256MB

来源: 高中教材