# 回旋连续整数打印

7 篇文章 0 订阅

3*3矩阵:

1 2 3

8 9 4

7 6 5

4*4矩阵:

1      2       3         4

12   13   14         5

11   16   15         6

10     9     8          7

Ubuntu Linux g++ 下编译通过:

#include <iostream>
#include <stdlib.h>
using namespace std;
//print matrixNum
void printMatrix(int **matrixNum,int n){
cout<<"Number matrix is as follows:"<<endl;
int i = 0;
int j;
for(;i < n;i++){
for(j = 0;j < n;j++){
cout<<matrixNum[i][j]<<"\t";
}
cout<<endl;
}
}

void calculateMatrix(int **matrixNum,int n){
int top = 0;
int down = n - 1;
int left = 0;
int right = n - 1;
int row = top;
int col;
matrixNum[0][0] = 1;
int temp = left;
while((top <= down)&&(left <= right)){
//calculate from left to right
for(col = temp;col < right;col++){
matrixNum[row][col+1] = matrixNum[row][col]+1;
}

//calculate from top to down
for(row = top++;row < down;row++){
matrixNum[row+1][col] = matrixNum[row][col] + 1;
}

//calculate from right to left
for(col = right--;col > left;col--){
matrixNum[row][col-1] = matrixNum[row][col] + 1;
}

//calculate from down to top
for(row = down--;row > top;row--){
matrixNum[row - 1][col] = matrixNum[row][col]  + 1;
}
temp = left;
left++;
}
}

int main(int argc,char**agrv){
int n;
cout<<"Please input an integer to define the length of the matrix row length:"<<endl;
cin>>n;

int **matrixNum = (int **)malloc(n*sizeof(int *));
int i = 0;
bool flag = false;
for(;i < n;i++){
matrixNum[i] = (int *)malloc(n*sizeof(int));
if(NULL == matrixNum[i]){
cout<<"memory allocation of matrixNum["<<i<<"]"<<"failed"<<endl;
flag = true;
break;
}
}
if(flag){
cout<<"Error:memory allocation of matrixNum failed."<<endl;
return -1;
}
calculateMatrix(matrixNum,n);
printMatrix(matrixNum,n);
for(i = 0;i < n;i++){
free(matrixNum[i]);
matrixNum[i] = NULL;
}
return 0;
}

2-6行

• 0
点赞
• 0
收藏
• 打赏
• 0
评论
05-31 1760
06-20 1523
04-19 3563
03-05 596
04-13 66
04-17 806
05-31 1万+
01-05 2192
09-07 2562
05-31 4564
12-11 3841
05-01 131
07-31 637
03-01 1937

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

acceptit8

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。