#include <stdio.h>
static int g_count;
static int g_count_swap;
void searchPosition(int(*ary)[3][6], int n, int* ref_x, int* ref_y) {
int x, y;
for(y = 0; y < 3; ++y) {
for(x = 0; x < 6; ++x) {
++g_count;
if((*ary)[y][x] == n) {
*ref_x = x;
*ref_y = y;
return;
}
}
}
}
void swapValue(int(*ary)[3][6], int x1, int y1, int x2, int y2) {
int temp = (*ary)[y1][x1];
(*ary)[y1][x1] = (*ary)[y2][x2];
(*ary)[y2][x2] = temp;
++g_count;
++g_count_swap;
}
void solve(int (*ary)[3][6]) {
int n;
int x, y;
int correct_x, correct_y;
int i;
g_count = 0;
g_count_swap = 0;
for(n = 1; n <= 18; ++n) {
x = -1;
y = -1;
searchPosition(ary, n, &x, &y);
if(x == -1 || y == -1) {
return -1;
}
correct_x = (n - 1) % 6;
correct_y = (n - 1) / 6;
if(x > correct_x) {
while(x > correct_x) {
swapValue(ary, x, y, x - 1, y);
--x;
}
}
else if(x < correct_x) {
while(x < correct_x) {
swapValue(ary, x, y, x + 1, y);
++x;
}
}
if(y > correct_y) {
while(y > correct_y) {
swapValue(ary, x, y, x, y - 1);
--y;
}
}
else if(y < correct_y) {
while(y < correct_y) {
swapValue(ary, x, y, x, y + 1);
++y;
}
}
}
}
void showArray(int(*ary)[3][6]) {
int x, y;
for(y = 0; y < 3; ++y) {
for(x = 0; x < 6; ++x) {
}
}
}
int main() {
int ary[3][6] = {
9, 18, 3, 4, 5, 13,
7, 8, 1, 10, 11, 6,
12, 14, 15, 16, 17, 2
};
int copy[3][6];
showArray(&ary);
memcpy(copy
, ary
, sizeof(ary
)); solve(©);
printf("after (%d counts / %d swaps) : \n", g_count
, g_count_swap
); showArray(©);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CgpzdGF0aWMgaW50IGdfY291bnQ7CnN0YXRpYyBpbnQgZ19jb3VudF9zd2FwOwoKdm9pZCBzZWFyY2hQb3NpdGlvbihpbnQoKmFyeSlbM11bNl0sIGludCBuLCBpbnQqIHJlZ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