Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2506134
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2011-04-13 18:24:19

    有这样一个包含9个圆圈的数字。将1~8这8个数字随机的填写到该数阵的外层圆圈中,只剩下中间的一个空圆圈。规定每个数字只能按照数阵中的直线中一个圆圈移动到另外一个空的圆圈中。通过若干步的移动,要求将该数字移动成为顺序的数字状态。编写程序,输出数字移动的每一步的过程。
    因为中间的圆圈是空的,所以使用中间的圆圈进行数据的移动。将数字移动到指定的位置。停止,进行下一次的移动操作。我们可以数组m[0]最终保存数字1,m[1]最终保存数字2...,m[7]最终保存数字8,因此使用冒泡排序进行,代码如下:
  1. #include <stdio.h>

  2. getStep(int m[])
  3. {
  4.   int i,j,tmp;
  5.   for(i=0; i<7; i++)
  6.     for(j=0; j<7-i; j++)
  7.       if(m[j] >=m[j+1]){
  8.         tmp = m[j];
  9.         m[j] = m[j+1];
  10.         m[j+1] = tmp;
  11.         
  12.         printf("%d#(%d)-->0#\n",j+1,m[j+1]);
  13.         printf("%d#(%d)-->%d#\n",j+2,m[j],j+1);
  14.         printf("0#-->%d#(%d)\n",j+2,m[j+2]);
  15.       }

  16.   printf("\n");
  17. }

  18. print(int m[])
  19. {
  20.   printf("[%d]--[%d]--[%d]\n",m[0],m[1],m[2]);
  21.   printf(" | %c | %c |\n",92,47);
  22.   printf("[%d]--[ ]--[%d]\n",m[7],m[3]);
  23.   printf(" | %c | %c |\n",47,92);
  24.   printf("[%d]--[%d]--[%d]\n",m[6],m[5],m[4]);
  25. }

  26. int main(int argc, char *argv[])
  27. {
  28.   int i,m[8];
  29.   printf("please input 8 integer(1~8) to arrange this matrix\n");
  30.   for(i=0; i<8; i++)
  31.     scanf("%d",&m[i]);
  32.   printf("the initial data matrix is like\n");
  33.   print(m);
  34.   printf("\nmove step:\n");
  35.   getStep(m);
  36.   printf("the result of moveing is\n");
  37.   print(m);

  38.   return 0;
  39. }
执行结果如下:
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./a.out 
please input 8 integer(1~8) to arrange this matrix
1 2 3 4 5 8 7 6
the initial data matrix is like
[1]--[2]--[3]
 |  \   |   /   |
[6]--[ ]--[4]
 |  /   |   \   |
[7]--[8]--[5]

move step:
6#(8)-->0#
7#(7)-->6#
0#-->7#(6)
7#(8)-->0#
8#(6)-->7#
0#-->8#(8)
6#(7)-->0#
7#(6)-->6#
0#-->7#(8)

the result of moveing is
[1]--[2]--[3]
 |  \   |   /   |
[8]--[ ]--[4]
 |  /   |   \   |
[7]--[6]--[5]

阅读(1773) | 评论(0) | 转发(0) |
0

上一篇:魔幻方阵

下一篇:数字的全排列

给主人留下些什么吧!~~