本文共 1519 字,大约阅读时间需要 5 分钟。
//在 n * n 方阵里填入 1, 2, …, n * n, 要求填成蛇形。例如 n = 4 时方阵为://10 11 12 1//9 16 13 2//8 15 14 3//7 6 5 4//要求:1.使用C++的相关函数根据 2.输入数字申请空间,不允许浪费空间#include#include void print(int** pt, int num, int count){ int rows = 0; int cols = 0; int x = 0;//行 int len = num*num; while (count <= len) { if (count <= len) { for (rows, cols = num - 1; rows < num; ++rows) { pt[rows][cols] = count; ++count; } --rows; --cols; } if (count <= len) { for (rows, cols; cols >= x; --cols) { pt[rows][cols] = count; ++count; } --rows; ++cols; } if (count <= len) { for (rows, cols; rows >= x; --rows) { pt[rows][cols] = count; ++count; } ++rows; ++cols; } if (count <= len) { for (rows, cols; cols < num - 1; ++cols) { pt[rows][cols] = count; ++count; } ++rows; --cols; --num;//向右打印减少一行 ++x;//向上打印减少一行 } } return;}int main(){ using namespace std; int num = 0; cout << "Input a sign_int num: "; cin >> num; int rows = 0; int cols = num - 1; int count = 1; //动态开辟 int** pt = new int*[num];//存地址 memset(pt, 0, sizeof(int*)*num); for (int i = 0; i < num; ++i)//存元素 { //int *row = new int[num];//存行的每个元素的数组 //p[0] = i; //pt[i] =row; pt[i] = new int[num]; memset(pt[i], 0, sizeof(int)*num); } print(pt, num, count); for (int i = 0; i < num; i++) { for (int j = 0; j < num; j++) { cout << pt[i][j]; cout << " "; } cout << "\n"; } system("pause"); //释放 for (int i = 0; i < num; ++i) { delete[] pt[i]; } delete[] pt; return 0;}
转载地址:http://zlypi.baihongyu.com/