代码如下
#include<iostream>
#include<fstream>
using namespace std;
//#define fin cin
int main()
{
//ifstream fin;
//fin.open("in.txt");
char puzzle[10][10];
char order;
int x = 0, y = 0;
int num_of_puzzles = 1;
cin.getline(puzzle[0], 7);
while (puzzle[0][0] != 'Z')
{
//输入第二至五行
for (int i = 1; i < 5; i++)
{
cin.getline(puzzle[i], 7);
}
//for循环找出空格位置,储存为(x,y)
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if ((puzzle[i][j] == ' ')||(puzzle[i][j] == '\0'))
{
x = i;
y = j;
}
}
}
//逐字符输入命令
cin >> order;
//声明状态变量
int status = 1;
//模拟法执行命令
while ((order != '0')&&(status))
{
status = 1;
switch (order)
{
case 'A':
if (x == 0)
{
status = 0;
break;
}
else
{
puzzle[x][y] = puzzle[x - 1][y];
puzzle[x - 1][y] = ' ';
x--;
}
break;
case 'B':
if (x == 4)
{
status = 0;
break;
}
else
{
puzzle[x][y] = puzzle[x + 1][y];
puzzle[x + 1][y] = ' ';
x++;
}
break;
case 'L':
if (y == 0)
{
status = 0;
break;
}
else
{
puzzle[x][y] = puzzle[x][y - 1];
puzzle[x][y - 1] = ' ';
y--;
}
break;
case 'R':
if (y == 4)
{
status = 0;
break;
}
else
{
puzzle[x][y] = puzzle[x][y + 1];
puzzle[x][y + 1] = ' ';
y++;
}
break;
default:
cout << "process wrong!\n";
break;
}
cin >> order;
}
while (order != '0')
{
cin >> order;
}
//for循环输出puzzle
if (num_of_puzzles > 1)cout << endl;
if (status)
{
cout << "Puzzle #" << num_of_puzzles << ":\n";
for (int i = 0; i < 5; i++)
{
for (int g = 0; g < 4; g++)
cout << puzzle[i][g] <<" ";
cout << puzzle[i][4] << endl;
}
}
else
{
cout << "Puzzle #" << num_of_puzzles << ":\n";
cout << "This puzzle has no final configuration.\n";
}
//输入第一行
num_of_puzzles++;
cin.get();
cin.getline(puzzle[0], 7);
}
//fin.close();
return 0;
}