【UVA – 227】Puzzle【紫书】

【UVA – 227】Puzzle【紫书】

【模拟】

问题链接:https://vjudge.net/problem/UVA-227

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

Solution:

按照题目要求,开一个二维数组模拟就好,分析对应指令,然后判断一下是否可以执行这个操作等。如果使用fgets,注意处理换行符。

#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;
}