C++面试题

1.输入一个n ,然后在屏幕上打印出NxN 的矩阵!

例如,输入一个3,则

1 2 3

8 9 4

7 6 5

输入一个4,则

1    2   3   4

12 13 14 5

11 16 15 6

10  9  8   7

#include <iostream> #include <iomanip> using namespace std; void PrintMatrix(int n) { if (n <= 1) { cout << n << endl; return; } //分配空间 int **matrix = new int*[n]; for (int i = 0; i < n; ++i) { matrix[i] = new int[n]; for (int j = 0; j < n; ++j) { matrix[i][j] = 0; } } int row = 0; int col = 0; int num = 1; int nend = n*n; char buff[256] = {"\0"}; _itoa_s(nend, buff, 256, 10); int width = strlen(buff); int nloop = 0; while (num <= nend) { //行 左->右 for (; col < n - nloop; ++col) { matrix[row][col] = num++; } //列 上->下 col -= 1; row += 1; for (; row < n - nloop; ++row) { matrix[row][col] = num++; } //行 右->左 row -= 1; col -= 1; for (; col >= nloop; --col) { matrix[row][col] = num++; } //列 下->上 col += 1; row -= 1; for (; row > nloop; --row) { matrix[row][col] = num++; } row = col = 0; ++nloop; row += nloop; col += nloop; } //打印输出 for (int k = 0; k < n; ++k) { for (int h = 0; h < n; ++h) { cout << setw(width) << matrix[k][h] << " "; } cout << endl; } //释放空间 for (int i = 0; i < n; ++i) { delete[] matrix[i]; matrix[i] = 0; } delete[] matrix; }

转载于:https://www.cnblogs.com/neking/archive/2011/12/21/2428165.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值