[C++日常小题] 三角螺旋数组

来源:互联网 发布:网络错误代码0013 编辑:程序博客网 时间:2024/05/08 10:12

三角螺旋数组输出示例

大小为 5 时输出:

1       2       3       4       512      13      14      611      15      710      89

大小为 7 时输出:

1       2       3       4       5       6       718      19      20      21      22      817      27      28      23      916      26      24      1015      25      1114      1213

代码

#include <iostream>#include <iomanip>#define SIZE 7  // 数组大小using std::cout;using std::endl;using std::setw;int main() {    int num[SIZE][SIZE] = {0}, flag = 0;  // flag变量用来标记赋值方向    int x = 0, y = 0, count = 1;  // 使用(x, y) 坐标来给数组赋值    while (count <= (SIZE + 1) * SIZE / 2) {  // 总的个数为 (1+n)*n/2 个(等差数列)        if (0 == flag) {  // 先水平向右赋值            // horizontal: flag == 0            for (int j = 0; j < SIZE; ++j) {                if (num[x][y] != 0) {  // 当碰到非 0 值时退出,下同                    break;                } else {                    num[x][y++] = count++;                }            }            x++, y -= 2;  // 更新(x, y) 为下一个方向做准备,下同            flag = 1;        } else if (1 == flag) {  // 斜向左下赋值            // hypotenuse: flag == 1            for (int j = 0; j < SIZE; ++j) {                if (y < 0 || num[x][y] != 0) {                    x--, y++;  // 第一次向左下赋值的时候y可能越界到-1,并且之后的斜向赋值碰                    break;     // 到不为0的值得位置时,要还原坐标                } else {                    num[x++][y--] = count++;                }            }            x--;            flag = 2;        } else {            // vertical: flag == 2            for (int j = 0; j < SIZE; ++j) {                if (num[x][y] != 0) {                    break;                } else {                    num[x--][y] = count++;                }            }            x++, y++;            flag = 0;        }    }    for (int i = 0; i < SIZE; ++i) {  // 输出        for (int j = 0; j < SIZE - i; ++j) {            cout << setw(5) << setiosflags(std::ios::left) << num[i][j];        }        cout << endl;    }    return 0;}

附加

通过使用(x, y)坐标来进行赋值,个人感觉比较易于理解和编写代码。另外经过搜索,看到了其他的方法,特此附上代码:

C语言实现

#include <stdio.h>#include <stdlib.h>#define N 4int main() {    int i = 0,j = 0, m, n, t = 1, a[N][N];    for(m = 0; m <= (int)(N / 2); m++) {        //N行螺旋共有N*(N+1)/2个数        for(j = m; j <= N - 1 - 2 * m; j++) { //横循环            a[m][j] = t++;        }        for(j = m + 1; j <= N - 1 - 2 * m; j++) { //斜边循环            a[j][N - 2 * m - (j - m) - 1] = t++;        }        for(j = N - 2 * m - 2; j >= m + 1; j--) { //竖列循环            a[j][m] = t++;        }    }    for(i = 0; i <= N - 1; i++) {        for(j = 0; j <= N - 1 - i; j++) {            printf("%5d", a[i][j]);        }        printf("\n");    }    system("PAUSE");}
0 0
原创粉丝点击