谜题(Puzzle, UVa 227)算法

这道题目比较简单,用数组模拟就行。

下面是根据《算法竞赛入门经典(第二版)》的题目简介编写的程序代码。

#include 
char mat[6][6];
char com[1000];
int spx, spy; //空格列和行 
int main()
{
	int i, flag = 1;
	while(gets(mat[0]))
	{
		flag = 1;
		for(i = 1; i < 5; i++)
		{
			gets(mat[i]);
		}
		gets(com); 
		for(int j = 0; j < 5; j++)
		{
			for(int k = 0; k < 5; k++)
			{
				if(mat[j][k] == ' ')
				{
					spy = j;
					spx = k;
				}
			}
		}
		i = 0;
		while(com[i] != '\0')
		{
			if(com[i] == 'A')
			{
				if(spy-1 < 0)
				{
					printf("This puzzle has no final configuration.\n");
					flag = 0;
					break;
				}
				else
				{
					mat[spy][spx] = mat[spy-1][spx];
					mat[--spy][spx] = ' ';
				}
			}
			if(com[i] == 'B')
			{
				if(spy+1 > 4)
				{
					printf("This puzzle has no final configuration.\n");
					flag = 0;
					break;
				}
				else
				{
					mat[spy][spx] = mat[spy+1][spx];
					mat[++spy][spx] = ' ';
				}
			}
			if(com[i] == 'L')
			{
				if(spx-1 < 0)
				{
					printf("This puzzle has no final configuration.\n");
					flag = 0;
					break;
				}
				else
				{
					mat[spy][spx] = mat[spy][spx-1];
					mat[spy][--spx] = ' ';
				}
			}
			if(com[i] == 'R')
			{
				if(spx+1 > 4)
				{
					printf("This puzzle has no final configuration.\n");
					flag = 0;
					break;
				}
				else
				{
					mat[spy][spx] = mat[spy][spx+1];
					mat[spy][++spx] = ' ';
				}
			}
			i++;
		}
		if(flag)
		{
			for(int j = 0; j < 5; j++)
			{
				for(int k = 0; k < 5; k++)
				{
					printf("%c", mat[j][k]);
				}
				printf("\n");
			}
		}
	}
	return 0;
}

测试输入

TRGSJ
XDOKI
M VLN
WPABE
UQHCF
ARRBBL0

测试输出

TRGSJ
XOKLI
MDVBN
WP AE
UQHCF


你可能感兴趣的:(算法竞赛入门经典(第2版),模拟)