处理紫书水题,代码比较丑,直接贴代码了。
#include<cstdio>
#include<algorithm>
#include<string>
#include<iostream>
using namespace std;
const int maxn = 10;
int flag = 1;
char cache[maxn][maxn];
int pos[3];
bool ok(int dr,int dc){
if(pos[1]+dr > 5||pos[1] + dr < 1|| pos[2] + dc > 5 || pos[2] + dc < 1)
{flag = 0;return false;}
return true;
}
bool Command(string &cmd){
for(int i = 0; i < cmd.length(); i++){
if(cmd[i] == '0') return false;
switch (cmd[i]){
case 'A': if(ok(-1,0)) {swap(cache[pos[1]][pos[2]],cache[pos[1]-1][pos[2]]);pos[1] -= 1;} break;
case 'B': if(ok(1,0)) {swap(cache[pos[1]][pos[2]],cache[1+pos[1]][pos[2]]);pos[1]++;}break;
case 'L': if(ok(0,-1)) {swap(cache[pos[1]][pos[2]],cache[pos[1]][pos[2]-1]); pos[2]--;} break;
case 'R': if(ok(0,1)) {swap(cache[pos[1]][pos[2]],cache[pos[1]][pos[2]+1]);pos[2]++;} break;
}
}
return true;
}
int main(){
int kase = 0;
string cmd;
while(true) {
flag = 1;
for(int r = 1; r <= 5; r++){
for(int c = 1; c <= 5; c++){
if(cache[1][1] == 'Z') return 0;
char c0 = getchar();
if(c0 == '\n'){
if(c == 5) {cache[r][c] = ' ';goto f;}
else c0 = getchar();
}
cache[r][c] = c0;
f:
if(cache[r][c] == ' ') {pos[1] = r; pos[2] = c;} //记录空格
}
}
if (kase++) printf("\n");
while(cin >> cmd){
if(!Command(cmd)) break;
}
printf("Puzzle #%d:\n", kase);
if(flag) {
for(int r = 1; r <= 5; r++){
for(int c = 1; c <= 5; c++){
if(c == 5) printf("%c\n",cache[r][c]);
else printf("%c ",cache[r][c]);
}
}
}
else printf("This puzzle has no final configuration.\n");
}
return 0;
}
本文提供了一种解决紫书水题的程序实现方案。通过使用C++编程语言,该方案详细介绍了如何处理特定的拼图游戏问题,包括读取初始状态、执行指令集以及检查最终状态是否有效。代码中涉及了数组操作、字符串处理和简单的状态判断。
1万+

被折叠的 条评论
为什么被折叠?



