蛇形数组打印(两种形式)

蛇形数组打印

第一种形式

  • 形式1
5
    1    2    3    4    5
   16   17   18   19    6
   15   24   25   20    7
   14   23   22   21    8
   13   12   11   10    9
请按任意键继续. . .
  • 形式2
5
   13   14   15   16    1
   12   23   24   17    2
   11   22   25   18    3
   10   21   20   19    4
    9    8    7    6    5
请按任意键继续. . .
  • 形式3
5
    9   10   11   12   13
    8   21   22   23   14
    7   20   25   24   15
    6   19   18   17   16
    5    4    3    2    1
请按任意键继续. . .
  • 形式4
5
   13   12   11   10    9
   14   23   22   21    8
   15   24   25   20    7
   16   17   18   19    6
    1    2    3    4    5
请按任意键继续. . .

完整代码

#include<iostream>
#include<stdlib.h>
#include <iomanip>

using namespace std;
/*打印函数*/
void my_printf(int arr[100][100],int num)
{
    int i, j;
    for (i = 0; i < num; i++)
    {
        for (j = 0; j < num; j++)
        {
            cout << setw(5) << arr[i][j];
        }
        cout << endl;
    }
}

int main()
{
    int arr[100][100] = { 0 };
    int i, j;
    int x, y;
    int num = 0;
    int count = 1;
    /*1的起始位置*/
    arr[x = 4][y = 0] = 1;
    cin >> num;//打印的列数
    /*判断起始位置的下一个数组是0&&没有越界。就置1*/
    for (i = 0; i < num*num; i++)
    {
        while (arr[x][y+1] == 0 && y + 1 < num)
            arr[x][++y] = ++count;
        while (arr[x+1][y] == 0 && x + 1< num)
            arr[++x][y] = ++count;
        while (arr[x][y-1] == 0 && y - 1 >= 0)
            arr[x][--y] = ++count;
        while (arr[x-1][y] == 0 && x - 1>= 0)
            arr[--x][y] = ++count;

    }
    my_printf(arr,num);

    system("pause");
}

第二种形式

5
1 3 6 10 15
2 5 9 14
4 8 13
7 12
11

完整代码

#include<iostream>

using namespace std;

int main()
{
    int N = 0;
    while (cin >> N) 
    {
        int i, k;
        int x = 1;
        int count = 1;
        for (i = 1; i <= N; i++)
        {
            count = x;
            cout << count;
            for (k = i + 1; k <= N; k++)
            {
                count = count + k;//首地址值
                cout << ' ';
                cout << count;
            }
            x += i;//1 2 4 7 11 计算每行第一个元素值
            cout << endl;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/csdn_kou/article/details/80371377