[C++][动动脑] 特殊矩阵 - 蛇行、螺旋、魔方阵

这是我大学程式设计课上的题目,最近整理电脑时被我挖出来,自己又重新做了一次,觉得蛮有趣的,给大家动动脑。

题目说明:
矩阵大小 SIZE 需可由变数或 #define 控制,範围 1 <= SIZE <= 9。

蛇行:
http://img2.58codes.com/2024/20106865bD8QXr8wnx.jpg

螺旋:
http://img2.58codes.com/2024/201068656f1ccSKmjj.jpg

魔方阵:
http://img2.58codes.com/2024/20106865QWklUiBXeD.jpg

程式码如下:

蛇行:

#include <stdio.h>#include <stdlib.h>#define SIZE 5int main(void){    int x, y;    int array[SIZE][SIZE] = {0};    for (int i = 0; i < SIZE * SIZE; i++)    {        x = i / SIZE;        //奇数列由小到大,偶数列由大到小        y = x % 2 == 0 ? i % SIZE : SIZE - 1 - i % SIZE;        array[x][y] = i + 1;    }    for (int i = 0; i < SIZE; i++)    {        for (int j = 0; j < SIZE; j++)        {            printf("%2d ", array[i][j]);        }        printf("\n");    }    system("pause");    return 0;}

螺旋:

#include <stdio.h>#include <stdlib.h>#define SIZE 5//走法偏移量: 右->下->左->上int dir_x[4] = {0, 1, 0, -1};int dir_y[4] = {1, 0, -1, 0};int main(void){    int index, x, y, temp_x, temp_y;    int array[SIZE][SIZE] = {0};    index = 0;    x = 0;    y = -1;    for (int i = 0; i < SIZE * SIZE; i++)    {        //试走,如果超出边界或遇到已经走过的格子,index + 1 转弯        temp_x = x + dir_x[index];        temp_y = y + dir_y[index];        if (temp_x < 0 || temp_x > SIZE - 1 ||             temp_y < 0 || temp_y > SIZE - 1 ||             array[temp_x][temp_y] != 0)        {            index = (index + 1) % 4;        }        //往下一个座标前进        x = x + dir_x[index];        y = y + dir_y[index];        array[x][y] = i + 1;    }    for (int i = 0; i < SIZE; i++)    {        for (int j = 0; j < SIZE; j++)        {            printf("%2d ", array[i][j]);        }        printf("\n");    }    system("pause");    return 0;}

魔方阵:

#include <stdio.h>#include <stdlib.h>#define SIZE 5int main(void){    int x, y;    int array[SIZE][SIZE] = {0};    x = 0;    y = SIZE / 2;    for (int i = 0; i < SIZE * SIZE; i++)    {        //如果超过斜对角,左下往右上的最后一格,或遇到已经走过的格子,就退回并往下        if ((x < 0 && y > SIZE - 1) ||            (x >= 0 && y <= SIZE - 1 && array[x][y] != 0))        {            x = x + 2;            y = y - 1;        }        //超过边界就将该轴座标移动到对面        x = (x + SIZE) % SIZE;        y = y % SIZE;        array[x][y] = i + 1;        //往右上前进        x = x - 1;        y = y + 1;    }    for (int i = 0; i < SIZE; i++)    {        for (int j = 0; j < SIZE; j++)        {            printf("%2d ", array[i][j]);        }        printf("\n");    }    system("pause");    return 0;}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章