VS2019堆栈溢出---定义了过大的数组,运行程序弹出chkstk.asm的解决方法
用new定义数组
首先要算出合适的m,n——行、列数
附:几个特殊的测试点,输入3个数、27个数、11个数
然后new一个二维数组,将给出的数套进去,
i=0;j=0;光标先向右,再向下,再向左,再向上,再向右...如何循环
给出四周的边界数——top = 0, left = -1, right = n, down = m;
再给出当前的轨迹方向—— r = 1, l = 0, up = 0, d = 0; (右左上下,1为当前轨迹方向)
如何退出循环,定义一个sum,统计当前已定好位置的数的个数,当sum == num时flag = 0,退出循环!
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int main() {
int num, i,j,k;
int m, n;
cin >> num;
//new一个number数组
int* arr = new int[num];
for (i = 0; i < num; i++) {
cin >> arr[i];
}
sort(arr, arr + num); // 降序排列
//获得m,n行列
n = abs(sqrt(num));
while (num % n != 0) {
n--;
}
m = num / n;
//new一个二维数组
int **a;
a = new int *[m];
for (i = 0; i < m; i++) {
a[i] = new int[n];
}
k = num - 1;
int size = num;
int top = 0, left = -1, right = n, down = m;
int r = 1, l = 0, up = 0, d = 0; // 光标左右上下
i = 0, j = 0;
int flag = 1, sum = 0;
while (flag) {
if (r) {
if (sum == num) {
flag = 0; break;
}
//0 1 2
if (j < right) {
a[i][j++] = arr[k--];
sum++;
}
if (j == right) {
i++; right--; j = right;
r = 0; d = 1;
}
}
if (d) {
if (sum == num) {
flag = 0; break;
}
if (i < down) {
a[i++][j] = arr[k--];
sum++;
}
if (i == down) {
j--; down--; i = down;
l = 1; d = 0;
}
}
if (l) {
if (sum == num) {
flag = 0; break;
}
if (j > left) {
a[i][j--] = arr[k--];
sum++;
}
if (j == left) {
i--; left++; j = left;
up = 1; l = 0;
}
}
if (up) {
if (sum == num) {
flag = 0; break;
}
if (i > top) {
a[i--][j] = arr[k--];
sum++;
}
if (i == top) {
j++; top++; i = top;
up = 0; r = 1;
}
}
}
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
cout << a[i][j];
if (j < n - 1) {
cout << " ";
}
}
cout << endl;
}
return 0;
}
再附一个网上的,似乎简单些,但我脑子不够用,还是用自己的笨方法吧,(* ̄︶ ̄)
// 1050 螺旋矩阵 (25 分).cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
int main()
{
//输入
int num;
cin >> num;
int a[num];
int tmp;
for (int i = 0; i < num; i++) {
cin >> tmp;
a[i] = tmp;
}
//排序
sort(a, a + num);
//求出行列数
int hang, lie;
lie = sqrt(num);
while (num % lie) lie--;
hang = num / lie;
//循环打印即可
int t[hang][lie];
int index = 0;
for (int side = 0, k = num - 1; side * 2 < lie; side++) {
for (int j = side; j < lie - side; j++) {
t[side][j] = a[k--];
}
for (int i = side + 1; i < hang - side; i++) {
t[i][lie - 1 - side] = a[k--];
}
for (int j = lie - 2 - side; j >= side; j--) {
t[hang - 1 - side][j] = a[k--];
}
if (lie - 1 - side > side) {
for (int i = hang - 2 - side; i >= side + 1; i--) {
t[i][side] = a[k--];
}
}
}
for (int i = 0; i < hang; i++) {
for (int j = 0; j < lie; j++) {
printf("%d", t[i][j]);
if (j + 1 < lie) {
printf(" ");
}
}
printf("\n");
}
}
原文地址:https://www.cnblogs.com/tanghm/p/12661689.html
时间: 2024-10-10 12:48:39