回旋连续整数打印

一问题:

顺时针打印连续自然数,实现类似如下的效果:

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行的:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值