Spiral matrix

Topic content:
A matrix output of a spiral n*n that turns counterclockwise from the inside out
enter description
The scale of the matrix, 0~50, such as 5 means a matrix with 5 rows and 5 columns

output description
The scale of the matrix, 0~50, such as 5 means a matrix with 5 rows and 5 columns, each number occupies 5 bits

input sample
5

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

code

/*
Descending from the largest number
*/
#include <iostream>
#include <stdio.h>
using namespace std;

int main(){
	int n, i, j, k = 0;
	int sum
	int a[100][100];
	
	cin >> n;
	
	sum = n * n;
	while(k <= n / 2){
		for(i = k; i <= n - k - 1; i++)
			a[k][i] = sum--;
		for(i = k + 1; i <= n - k - 1; i++)
			a[i][n - k - 1] = sum--;
		for(i = n - k - 2; i >= k; i--)
			a[n - k - 1][i] = sum--;
		for(i = n - k - 2; i >= k + 1; i--)
			a[i][k] = sum--;
		k++;
	}
	
	for(i = 0; i < n; i++){
		for(j = 0; j < n; j++){
			 if(j==0)  
                printf("%d",a[i][j]);  
            else  
                printf("%5d",a[i][j]);
		}
		cout << endl;
	}
		
}
 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325786402&siteId=291194637