2013年8月30日

UVa 227 - Puzzle

WA + RE for almost 20 times on this easy problem, only beacuse of this code.
while (gets(puzzle[0]) && puzzle[0][1]) {
  if (!first) {
    puts("");
  }
  first = false;
  int sr = -1, sc;
  for (int r = 1; r < 5; r++) {
    gets(puzzle[r]);
    for (int c = 0; c < 5; c++) {
      if (puzzle[r][c] == ' ') {
        sr = r;
        sc = c;
      }
    }
I forgot to check the space in row 0 Orz.
#include <cstdio>
#include <cstring>

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

int main() {
  int dr[128], dc[128];
  dr['A'] = -1, dc['A'] = 0;
  dr['B'] = 1, dc['B'] = 0;
  dr['L'] = 0, dc['L'] = -1;
  dr['R'] = 0, dc['R'] = 1;
  char puzzle[9][9];
  int C = 1;
  while (gets(puzzle[0]) && puzzle[0][1]) {
    if (C > 1) {
      puts("");
    }
    int sr = -1, sc;
    for (int r = 1; r < 5; r++) {
      gets(puzzle[r]);
    }
    for (int r = 0; r < 5; r++) {
      for (int c = 0; c < 5; c++) {
        if (puzzle[r][c] == ' ') {
          sr = r;
          sc = c;
        }
      }
    }
    bool legal = true;
    char ch;
    while (ch = getchar()) {
      if (ch == ' ' || ch == '\n') {
        continue;
      } else if (ch == '0') {
        getchar();
        break;
      } else if (ch != 'A' && ch != 'B' && ch != 'L' && ch != 'R') {
        legal = false;
      } else if (legal) {
        int nr = sr + dr[ch], nc = sc + dc[ch];
        if (check(nr, nc)) {
          puzzle[sr][sc] = puzzle[nr][nc];
          puzzle[nr][nc] = ' ';
          sr = nr;
          sc = nc;
        } else {
          legal = false;
        }
      }
    }
    printf("Puzzle #%d:\n", C++);
    if (legal) {
      for (int r = 0; r < 5; r++) {
        for (int c = 0; c < 5; c++) {
          printf("%c%s", puzzle[r][c], c == 4 ? "\n" : " ");
        }
      }
    } else {
      puts("This puzzle has no final configuration.");
    }
  }
  return 0;
}

沒有留言:

張貼留言