C语言趣味程序(15)

xiaoxiao2021-02-28  91

       今天来一道有些难度的题吧!        题目:数字移动        在图中的九个点上,空出中间的点,其余的点上任意填入数字1至8;1的位置固定不动,然后移动其余的数字,使1到8顺时针从小到大排列。移动的规则是:只能将数字沿线移向空白的点。                程序如下:  

#include <stdio.h> int a[] = {0, 1, 2, 5, 8, 7, 6, 3}; int b[9]; int c[9]; int count = 0; int main() { int i, j, k, t; void print(); printf("Please enter the numbers: "); for (i = 0; i < 8; i++) { scanf("%d", &b[a[i]]); } print(); for (t = -1, j = 0; j < 8 && t == -1; j++) { if (b[a[j]] == 1) { t = j; } } for (j = 0; j < 8; j++) { c[j] = a[(j + t) % 8]; } for (i = 2; i < 9; i++) { for (j = i - 1; j < 8; j++) { if (b[c[j]] == i && j != i - 1) { b[4] = j; b[c[j]] = 0; print(); for (k = j; k != i - 1; k--) { b[c[k]] = b[c[k - 1]]; b[c[k - 1]] = 0; print(); } b[c[k]] = i; b[4] = 0; print(); break; } else if (b[c[j]] == i) { break; } } } return 0; } void print(void) { int c; for (c = 0; c < 9; c++) { if (c % 3 == 2) { printf("-\n", b[c]); } else { printf("-", b[c]); } } printf("-------\n", count++); }

程序运行结果如下:

Please enter the numbers: 8 5 6 3 2 1 7 4 8 5 6 4 0 3 7 1 2 --- 0--- 8 5 6 4 7 3 7 1 0 --- 1--- 8 5 6 4 7 0 7 1 3 --- 2--- 8 5 0 4 7 6 7 1 3 --- 3--- 8 0 5 4 7 6 7 1 3 --- 4--- 0 8 5 4 7 6 7 1 3 --- 5--- 4 8 5 0 7 6 7 1 3 --- 6--- 4 8 5 7 7 6 0 1 3 --- 7--- 4 8 5 7 0 6 2 1 3 --- 8--- 4 8 5 7 7 6 2 1 0 --- 9--- 4 8 5 7 7 0 2 1 6 ---10--- 4 8 0 7 7 5 2 1 6 ---11--- 4 0 8 7 7 5 2 1 6 ---12--- 0 4 8 7 7 5 2 1 6 ---13--- 7 4 8 0 7 5 2 1 6 ---14--- 7 4 8 3 0 5 2 1 6 ---15--- 7 0 8 3 4 5 2 1 6 ---16--- 0 7 8 3 4 5 2 1 6 ---17--- 4 7 8 3 0 5 2 1 6 ---18--- 4 7 8 3 6 0 2 1 6 ---19--- 4 7 0 3 6 8 2 1 6 ---20--- 4 0 7 3 6 8 2 1 6 ---21--- 4 5 7 3 0 8 2 1 6 ---22--- 4 5 7 3 7 8 2 1 0 ---23--- 4 5 7 3 7 0 2 1 8 ---24--- 4 5 0 3 7 7 2 1 8 ---25--- 4 5 6 3 0 7 2 1 8 ---26---
转载请注明原文地址: https://www.6miu.com/read-38045.html

最新回复(0)