一问题:
顺时针打印连续自然数,实现类似如下的效果:
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行
来个30行的: