问题描述
p227原题链接:UVaOJ 227 - Puzzle
相关说明:本题为《算法竞赛入门经典(第2版)》习题 3-5
解法一:模拟
本题难度在于没难度,都是繁琐的输入输出 case 考虑,是那种 “题目很好,但下次不要再出了” 的类型,对于顺序刷紫书的新手来说,如果无法耐心地处理好数据 I/O, 会有些劝退。
- 写入 frame 数据时,注意第一行已经在外层 while 判断是否为 Z 时读入了,需要特判;
- 操作序列 seq 中可能会有非法操作,但不要立即 break, 否则会读不到序列终止符,也就是 0;
- 注意操作序列可能是多行的,意味着其中可能有空行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
#include <bits/stdc++.h> using namespace std; int main() { array<array<char, 5>, 5> frame = {0}; int game_cnt = 0; string line; while (getline(cin, line)) { if (line[0] == 'Z' && line.length() == 1) break; cout << (game_cnt++ ? "\n" : ""); cout << "Puzzle #" << game_cnt << ":" << endl; // Input the frame: int r, c; for (int i = 0; i < 5; ++i) { if (i) getline(cin, line); for (int j = 0; j < 5; ++j) { frame[i][j] = line[j]; if (line[j] == ' ') r = i, c = j; } } // Process the frame: string seq; bool legal = true, end = false; while (!end && getline(cin, seq)) { for (auto ch : seq) { if (ch == 'A' && r - 1 >= 0) { swap(frame[r][c], frame[r - 1][c]); r -= 1; } else if (ch == 'B' && r + 1 < 5) { swap(frame[r][c], frame[r + 1][c]); r += 1; } else if (ch == 'L' && c - 1 >= 0) { swap(frame[r][c], frame[r][c - 1]); c -= 1; } else if (ch == 'R' && c + 1 < 5) { swap(frame[r][c], frame[r][c + 1]); c += 1; } else if (ch == '0') { end = true; } else { legal = false; } } } // Output: if (legal) { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) cout << frame[i][j] << (j == 4 ? "\n" : " "); } } else { cout << "This puzzle has no final configuration." << endl; } } return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
frame = [[' ' for _ in range(5)] for _ in range(5)] game_cnt = 0 while True: line = input() if line == "Z": break game_cnt += 1 print("\n" if game_cnt > 1 else "", end="") print("Puzzle #{game_cnt}:") for i in range(5): line = input() if i else line for j in range(5): frame[i][j] = line[j] if line[j] == " ": r, c = i, j legal = True end = False while not end: seq = input() for ch in seq: if ch == "A" and r - 1 >= 0: frame[r][c], frame[r - 1][c] = frame[r - 1][c], frame[r][c] r -= 1 elif ch == "B" and r + 1 < 5: frame[r][c], frame[r + 1][c] = frame[r + 1][c], frame[r][c] r += 1 elif ch == "L" and c - 1 >= 0: frame[r][c], frame[r][c - 1] = frame[r][c - 1], frame[r][c] c -= 1 elif ch == "R" and c + 1 < 5: frame[r][c], frame[r][c + 1] = frame[r][c + 1], frame[r][c] c += 1 elif ch == "0": end = True else: legal = False if legal: for i in range(5): for j in range(5): print(frame[i][j], end=("\n" if j == 4 else " ")) else: print("This puzzle has no final configuration.") |