小紫书 习题 3-5(UVA 227) 谜题(Puzzle)

模拟整个过程,长度为5我就傻傻地开了[5][5]的数组,醉了,忘了是字符串长度+1吗…

还有就是读入那串操作指令之后,我是读到0结束的,但是我其他地方用的gets,所以要把0后面那个回车也吸收一下。。。

最后在输出格式上WA了。。。也是没有想到,,,是我的锅…

WA的一个原因就是,每个情况输出后要额外加一个空行,但是最后一个情况后面不能有空行,否则就会WA,

所以解决办法是,除了第一个之外,其他的情况在开始输出前,都先输出一个空行,就ok了

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
int main()
{
//	freopen("input.txt", "r", stdin);
	int cnt = 0;
	char puzzle[5][6];
	char oper[1000];
	while (1)
	{
		memset(puzzle, 0, sizeof(puzzle));
		memset(oper, 0, sizeof(oper));
		gets(puzzle[0]);
		if (puzzle[0][0] == 'Z'&&puzzle[0][1] == '\0')
			break;
		for (int i = 1; i < 5; i++)
			gets(puzzle[i]);
		/*for (int i = 0; i < 5; i++)
		{
			for (int j = 0; j < 5; j++)
			{
				if (j != 0)
					printf(" ");
				printf("%c", puzzle[i][j]);
			}
			printf("\n");
		}*/
		int bx = -1, by = -1;
		for (int i = 0; i < 5; i++)
		{
			for (int j = 0; j < 5; j++)
			{
				if (puzzle[i][j] == ' ' || puzzle[i][j] == '\0')
				{
					puzzle[i][j] = ' ';
					bx = i;
					by = j;
					break;
				}
			}
		}
		int opn = 0, c;
		bool flag = 0;
		while (c = getchar())
		{
			if (c == '0')
				break;
			if (c == 'A' || c == 'B' || c == 'L' || c == 'R')
				oper[opn++] = c;
		}
		while (c = getchar())
		{
			if (c == '\n')
				break;
		}
		/*for (int i = 0; i < opn; i++)
			printf("%c", oper[i]);
		printf("\n");*/
		for (int i = 0; i < opn; i++)
		{
			if (flag)
				break;
			switch (oper[i])
			{
			case 'A':
				if (bx <= 0)
					flag = 1;
				else
				{
					puzzle[bx][by] = puzzle[bx - 1][by];
					bx--;
					puzzle[bx][by] = ' ';
				}
				break;
			case 'B':
				if (bx >= 4)
					flag = 1;
				else
				{
					puzzle[bx][by] = puzzle[bx + 1][by];
					bx++;
					puzzle[bx][by] = ' ';
				}
				break;
			case 'L':
				if (by <= 0)
					flag = 1;
				else
				{
					puzzle[bx][by] = puzzle[bx][by - 1];
					by--;
					puzzle[bx][by] = ' ';
				}
				break;
			case 'R':
				if (by >= 4)
					flag = 1;
				else
				{
					puzzle[bx][by] = puzzle[bx][by + 1];
					by++;
					puzzle[bx][by] = ' ';
				}
				break;
			}
			if (flag)
			{
//				printf("i %d bx %d by %d\n", i, bx, by);
			}
		}
		if (cnt++)
			printf("\n");
		printf("Puzzle #%d:\n", cnt);
		if (flag)
		{
			printf("This puzzle has no final configuration.\n");
		}
		else
		{
			for (int i = 0; i < 5; i++)
			{
				for (int j = 0; j < 5; j++)
				{
					if (j != 0)
						printf(" ");
					printf("%c", puzzle[i][j]);
				}
				printf("\n");
			}
		}
	}
//	while (1);
//	system("pause");
	return 0;
}


你可能感兴趣的:(水题,小紫书)