算法和数据结构 打印回形矩阵
void print(int n) { if(n == 0) return; int row = 0, col = 0, cur_val = 1; int **arr = new int *[n]; for (int i = 0; i < n; i++) { arr[i] = new int[n]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = 0; } } while (cur_val <= n * n) { // 向右 while (row >= 0 && row <= n - 1 && col >= 0 && col <= n - 1 && arr[row][col] == 0) { arr[row][col] = cur_val++; col++; } row++; col--; // 向下 while (row >= 0 && row <= n - 1 && col >= 0 && col <= n - 1 && arr[row][col] == 0) { arr[row][col] = cur_val++; row++; } row--; col--; // 向左 while (row >= 0 && row <= n - 1 && col >= 0 && col <= n - 1 && arr[row][col] == 0) { arr[row][col] = cur_val++; col--; } row--; col++; // 向上 while (row >= 0 && row <= n - 1 && col >= 0 && col <= n - 1 && arr[row][col] == 0) { arr[row][col] = cur_val++; row--; } row++; col++; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << arr[i][j] << ' '; } cout << endl; } }