## 【UVA – 227】Puzzle【紫书】

【UVA – 227】Puzzle【紫书】

【模拟】

udebug数据连接：https://www.udebug.com/UVa/227

Solution:

```#include <iostream>

using namespace std;

const int LIM = 6;
char map[LIM][LIM];
int r, c;
/* The direction vector */
enum {A, B, R, L};
const struct Vector {
int r, c;
} dirs[] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

/* clear the rest '\n' */
inline void clsln() {
char tmp;
while ((tmp = getchar()) != '\n');
}

inline void swap(char &a, char &b) {
char tmp = a;
a = b;
b = tmp;
}

inline char myGetChar() {
char ret;
while ((ret = getchar()) == '\n' || ret == '\t' || ret == ' ');
return ret;
}

inline bool isValid(int r, int c) {
return r < 5 && r >= 0 && c < 5 && c >= 0;
}

bool move(char op) {
int nr = r, nc = c;
if (op == 'A') nr += dirs[A].r;
else if (op == 'B') nr += dirs[B].r;
else if (op == 'R') nc += dirs[R].c;
else if (op == 'L') nc += dirs[L].c;
if (isValid(nr, nc)) {
swap(map[nr][nc], map[r][c]);
r = nr, c = nc;
} else {
return false;
}
return true;
}

int main(void) {
for (int k = 1; fgets(map[0], LIM, stdin); k++) {
if (map[0][0] == 'Z') break;
clsln();
/* Separate output from different puzzle records by one blank line. */
if (k - 1) putchar('\n');
printf("Puzzle #%d:\n", k);
for (int i = 1; i <= 4; i++) {
fgets(map[i], LIM, stdin);
clsln();
}
/* to find the space */
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
if (map[i][j] == ' ')
r = i, c = j;
/* move */
char op;
bool flag = true;
while (~(op = myGetChar()) && op != '0')
flag = flag && move(op);
clsln();
/* output */
if (flag) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j) putchar(' ');
putchar(map[i][j]);
}
putchar('\n');
}
} else {
printf("This puzzle has no final configuration.\n");
}
}
return 0;
}```