Imagination |
Time Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:65536KB |
Total submit users: 81, Accepted users: 75 |
Problem 11081 : No special judgement |
Problem description |
There are four matrixs blow , Can you image the NEXT matrix from the given information?
|
Input |
The first line is a integer which represents the case number . For each test case , there will be a line which contains a integer N (1<=N<=100). |
Output |
Output the matrix which has N*N integers. Be careful that there is a blank space between two integer but no blank space after the last integer in a line. |
Sample Input |
4 1 2 3 4 |
Sample Output |
1 1 2 4 3 1 2 3 8 7 4 9 6 5 1 2 3 4 12 11 10 5 13 14 9 6 16 15 8 7 |
算法分析:一个递归程序,每次走一个周期,不过每次都要判断,是否已经到了边界了
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 #include<iostream>
2 #define N 110
3 using namespace std;
4
5 int a[N][N];
6
7 void work(int r,int c,int m,int first,int last)
8 {
9 int i;
10 if(first>last) return ;
11 for(i=1;i<=c+m-1&&first<=last;i++)
12 {
13 a[r][i]=first;first++;
14 }
15 for(i=r+1;i<=r+m-1&&first<=last;i++)
16 {
17 a[i][c+m-1]=first;first++;
18 }
19 for(i=r+m-1;i>=r+1&&first<=last;i--)
20 {
21 a[i][c+m-2]=first;first++;
22 }
23 for(i=c+m-3;i>=c&first<=last;i--)
24 {
25 a[r+1][i]=first;first++;
26 }
27 work(r+2,c,m-2,first,last);
28 }
29
30 int main()
31 {
32 int test;
33 cin>>test;
34 while(test--)
35 {
36 int n,i,j;
37 cin>>n;
38 work(1,1,n,1,n*n);
39 for(i=1;i<=n;i++)
40 {
41 for(j=1;j<n;j++)
42 {
43 cout<<a[i][j]<<" ";
44 }
45 cout<<a[i][j]<<endl;
46 }
47 }
48 }