C++面试题

来源:互联网 发布:淘宝网山地自行车配件 编辑:程序博客网 时间:2024/06/12 20:04

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;}