fork download
  1. #include <stdio.h>
  2.  
  3. static int g_count;
  4. static int g_count_swap;
  5.  
  6. void searchPosition(int(*ary)[3][6], int n, int* ref_x, int* ref_y) {
  7. int x, y;
  8.  
  9. for(y = 0; y < 3; ++y) {
  10. for(x = 0; x < 6; ++x) {
  11. ++g_count;
  12. if((*ary)[y][x] == n) {
  13. *ref_x = x;
  14. *ref_y = y;
  15. return;
  16. }
  17. }
  18. }
  19. }
  20.  
  21. void swapValue(int(*ary)[3][6], int x1, int y1, int x2, int y2) {
  22. int temp = (*ary)[y1][x1];
  23.  
  24. (*ary)[y1][x1] = (*ary)[y2][x2];
  25. (*ary)[y2][x2] = temp;
  26. ++g_count;
  27. ++g_count_swap;
  28. }
  29.  
  30. void solve(int (*ary)[3][6]) {
  31. int n;
  32. int x, y;
  33. int correct_x, correct_y;
  34. int i;
  35.  
  36. g_count = 0;
  37. g_count_swap = 0;
  38.  
  39. for(n = 1; n <= 18; ++n) {
  40. x = -1;
  41. y = -1;
  42. searchPosition(ary, n, &x, &y);
  43.  
  44. if(x == -1 || y == -1) {
  45. return -1;
  46. }
  47.  
  48. correct_x = (n - 1) % 6;
  49. correct_y = (n - 1) / 6;
  50.  
  51. if(x > correct_x) {
  52. while(x > correct_x) {
  53. swapValue(ary, x, y, x - 1, y);
  54. --x;
  55. }
  56. }
  57. else if(x < correct_x) {
  58. while(x < correct_x) {
  59. swapValue(ary, x, y, x + 1, y);
  60. ++x;
  61. }
  62. }
  63.  
  64. if(y > correct_y) {
  65. while(y > correct_y) {
  66. swapValue(ary, x, y, x, y - 1);
  67. --y;
  68. }
  69. }
  70. else if(y < correct_y) {
  71. while(y < correct_y) {
  72. swapValue(ary, x, y, x, y + 1);
  73. ++y;
  74. }
  75. }
  76. }
  77. }
  78.  
  79.  
  80. void showArray(int(*ary)[3][6]) {
  81. int x, y;
  82.  
  83. for(y = 0; y < 3; ++y) {
  84. for(x = 0; x < 6; ++x) {
  85. printf("%2d ", (*ary)[y][x]);
  86. }
  87. printf("\n");
  88. }
  89. }
  90.  
  91. int main() {
  92. int ary[3][6] = {
  93. 9, 18, 3, 4, 5, 13,
  94. 7, 8, 1, 10, 11, 6,
  95. 12, 14, 15, 16, 17, 2
  96. };
  97. int copy[3][6];
  98.  
  99. printf("sorce : \n");
  100. showArray(&ary);
  101.  
  102. memcpy(copy, ary, sizeof(ary));
  103. solve(&copy);
  104. printf("after (%d counts / %d swaps) : \n", g_count, g_count_swap);
  105. showArray(&copy);
  106.  
  107. return 0;
  108. }
Success #stdin #stdout 0s 2296KB
stdin
Standard input is empty
stdout
sorce : 
 9 18  3  4  5 13 
 7  8  1 10 11  6 
12 14 15 16 17  2 
after (252 counts / 30 swaps) : 
 1  2  3  4  5  6 
 7  8  9 10 11 12 
13 14 15 16 17 18