首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

HELP!该怎么处理

2012-03-01 
HELP!!!输入一个自然数N(2≤N≤9),要求输出如下的魔方阵,即边长为N*N,元素取值为1至N*N,1在左上角,呈顺时针

HELP!!!
输入一个自然数N(2≤N≤9),要求输出如下的魔方阵,即边长为N*N,元素取值为1至N*N,1在左上角,呈顺时针方向依次放置各元素。
N=3时:
1 2 3
8 9 4
7 6 5
【输入形式】
从标准输入读取一个整数N。 
【输出形式】
向标准输出打印结果。输出符合要求的方阵,每个数字占5个字符宽度,向右对齐,在每一行末均输出一个回车符。
【输入样例】 
4
【输出样例】
 1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7 

这道题怎么做啊,小弟在学ACM,请各位指教啊??用C来编。

[解决办法]
请教一下:ACM是什么?

C/C++ code
#include  <stdio.h> 

#define MINN 2
#define MAXN 9

enum direction
{
  up,
  down,
  left,
  right
};

int main( void )
{
  int n;
  int number, number_max;
  int x, y;
  int boundary_top, boundary_bottom, boundary_left, boundary_right;
  int matrix[MAXN][MAXN];
  enum direction current_direction = right;

  printf( "Please input n (%d~%d) : ", MINN, MAXN );
  scanf( "%d", &n );
  if ((n < MINN) || (n > MAXN))
    return 1;

  boundary_top = 0;
  boundary_bottom = n - 1;
  boundary_left = 0;
  boundary_right = n - 1;
  x = 0;
  y = 0;
  number_max = n * n;

  for (number = 1; number <= number_max; number++)
  {
    matrix[x][y] = number;

    switch (current_direction)
    {
    case right:
      if (++x == boundary_right)
      {
        current_direction = down;
        boundary_top++;
      }
      break;
    case down:
      if (++y == boundary_bottom)
      {
        current_direction = left;
        boundary_right--;
      }
      break;
    case left:
      if (--x == boundary_left)
      {
        current_direction = up;
        boundary_bottom--;
      }
      break;
    case up:
      if (--y == boundary_top)
      {
        current_direction = right;
        boundary_left++;
      }
      break;
    default:
      break;
    }
  }

  for (y = 0; y < n; y++)
  {
    for (x = 0; x < n; x++)
    {
      printf( "%5d", matrix[x][y] );
    }
    printf( "\n" );
  }

  return 0;
}

[解决办法]
在ACM中,这样分析:
 
第1个circle 数量为4n-4,即 4(n-0)-4
第2个circle n'=n-2,数量4n'-4=4(n-2)-4=4n-12
第3个circle n''=n-4,数量4''-4=4(n-4)-4=4n-20
......
可得每circle的数量为4(n-(i-1)*2)-4,i为第几圈

由于最后1圈要么=4,要么=0(n为奇数,这圈只有值n*n,不计),所以可知 i=INT(n/2)

这样,你就建立了所谓的模型

接下来,ok,就随便你怎么写程序了

热点排行