谜题(Puzzle)
算法标签:模拟+字符串+枚举
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int row, col;
int i, j;
int num = 1, len;
char temp;
int count;
while (1)
{
char str[5][5];
gets(str[0]);
if (str[0][0] == 'Z')
break;
gets(str[1]);
gets(str[2]);
gets(str[3]);
gets(str[4]);
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
{
if (str[i][j] == ' ')
{
row = i, col = j;
}
}
char arr[1000];
i = 0;
while (scanf("%c", &arr[i]) != EOF && arr[i] != '0')
{
i++;
}
len = i;
if (num > 1)
{
printf("\n");
}
for (i = 0; i < len; i++)
{
if (row == 0 && arr[i] == 'A' || row == 4 && arr[i] == 'B' || col == 0 && arr[i] == 'L' || col == 4 && arr[i] == 'R')
{
printf("Puzzle #%d:\n", num);
printf("This puzzle has no final configuration.\n");
num++;
memset(str, 0, sizeof str);
memset(arr, 0, sizeof arr);
getchar(); //吸回车
break;
}
else
{
if (arr[i] == 'A')
{
temp = str[row - 1][col];
str[row - 1][col] = ' ';
str[row][col] = temp;
row = row - 1;
col = col;
}
else if (arr[i] == 'B')
{
temp = str[row + 1][col];
str[row + 1][col] = ' ';
str[row][col] = temp;
row = row + 1;
col = col;
}
else if (arr[i] == 'L')
{
temp = str[row][col - 1];
str[row][col - 1] = ' ';
str[row][col] = temp;
row = row;
col = col - 1;
}
else if (arr[i] == 'R')
{
temp = str[row][col + 1];
str[row][col + 1] = ' ';
str[row][col] = temp;
row = row;
col = col + 1;
}
}
}
if (len == i)
{
printf("Puzzle #%d:\n", num);
for (i = 0; i < 5; i++)
{
count = 0;
for (j = 0; j < 5; j++)
{
if (count == 0)
{
printf("%c", str[i][j]);
count = 1;
}
else
{
printf(" %c", str[i][j]);
}
}
printf("\n");
}
num++;
memset(str, 0, sizeof str);
memset(arr, 0, sizeof arr);
getchar(); //吸回车
}
}
return 0;
}