首页 | 编程语言 | 网站建设 | 游戏天堂 | 冲浪宝典 | 网络安全 | 操作系统 | 软件时空 | 硬件指南 | 病毒相关 | IT 认证
软讯网络 > 编程语言 > C/C++ > 幻方算法与程序实现
【标  题】:幻方算法与程序实现
【关键字】:
【来  源】:http://www.cublog.cn/u/22837/showart.php?id=195959

幻方算法与程序实现

算法:
    口诀: 一立首行中, 右一上一, 受阻下一
比如3阶:
8 1 6
3 5 7
4 9 2

魔方阵算法:
(1)将1放在第一行中间一列
(2)从2开始直到n*n止个数一次按下列规则存放,每一个数存放的行比前一个数的列数减1,行数加1
(3)如果上一数的行数为1,,则下一个数的行数为n
(4)当上一个数的列数为n时,下一个数的列数应为1,行数减1
(5)如果按上面的规则确定的位置上已有数,或上一个数是第一行的n列时,则把下一个数放在上一个数的下面
实现:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int i;
    int n = 0;
    int width;
    int row, col;
    int *array;
    char buf[64];

    if (argc != 2) {
        printf("usage:\n");
        printf("\t%s <an odd number>\n", argv[0]);
        return 1;
    }

    n = atoi(argv[1]);
    if ((n & 1) == 0) {
        printf("error: odd number expected\n");
        return 1;
    }

    array = (int *)malloc(n * n * sizeof(int));
    if (array == NULL) {
        perror("malloc()");
        return 1;
    }

    for (i = 0; i < n * n; i++) {
        array[i] = 0;
    }

    for (i = 1, row = 0, col = n >> 1; i <= n * n; i++) {
        array[row * n + col] = i;
        if (array[(row + n - 1) % n * n + (col + 1) % n]) {
            row = (row + 1) % n;
        } else {
            row = (row + n - 1) % n;
            col = (col + 1) % n;
        }
    }

    sprintf(buf, "%d", n * n);
    width = 1 + strlen(buf);

    for (row = 0; row < n; row++) {
        for (col = 0; col < n; col++) {
            printf("%*d", width, array[row * n + col]);
        }
        printf("\n");
    }

    return 0;
}

运行示例:

 $ ./magic 5
 17 24  1  8 15
 23  5  7 14 16
  4  6 13 20 22
 10 12 19 21  3
 11 18 25  2  9

 
 
文件属性:【上一篇】
jBPM小知识:【下一篇】
【相关文章】
没有相关文章
【随机文章】
  • DW MX 2004更多新增功能
  • ogre和physx二sdk整合笔记
  • C程序设计的常用算法
  • Resin2.1.12的数据库连接池配置
  • 《设计模式精解》读后感
  • 店伙躬身陪笑道
  • 动网论坛有史以来最大的安全漏洞(1)
  • UDP检验和
  • [UMU WSH 教程](12)常见对象 - InternetExplorer.Application
  • Struts 之 DispatchAction
  • 【相关评论】
    没有相关评论
    【发表评论】
    姓名:
    邮件:
    随机码*
    评论*
          
    |  首 页  |  版权声明  |  联系我们   |  网站地图  |
    CopyRight © 2004-2007 软讯网络 All Rigths Reserved.