欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

谜题 Puzzle ,ACM/ICPC World Finals 1993, UVa227

程序员文章站 2024-03-19 19:26:46
...

谜题 Puzzle ,ACM/ICPC World Finals 1993, UVa227
提交一次就AC的源代码

#include <iostream>
#include <algorithm>
#include <cstdbool>
using namespace std;
typedef struct pos
{
	int posx;
	int posy;
}pos;
int main()
{
	char input;
	int num = 1;
	while ((input = cin.get()) != 'Z')
	{
		if (num != 1)
			cout << endl;
		cout << "Puzzle #" << num++ << ":" << endl;
		char grid[5][5];
		pos space = { 0,0 };
		bool valid = 1;
		for (int i = 0; i < 5; ++i)
		{
			for (int j = 0; j < 5; ++j)
			{
				if (i != 0 || j != 0)
				{
					input = cin.get();
				}
				if (input == '\n')
				{
					if (j == 4) {
						input = ' ';
					}
					else
						input = cin.get();
				}
				grid[i][j] = input;
				if (grid[i][j] == ' ')
				{
					space.posx = i;
					space.posy = j;
				}
			}
		}
		while ((input = cin.get()) != '0')
		{
			if (input == '\n')
				continue;
			if (valid == 1) {
				if (input == 'A')
				{
					if (space.posx - 1 >= 0)
					{
						swap(grid[space.posx - 1][space.posy], grid[space.posx][space.posy]);
						space.posx -= 1;
					}
					else
					{
						valid = 0;
					}
				}
				if (input == 'B')
				{
					if (space.posx + 1 < 5)
					{
						swap(grid[space.posx + 1][space.posy], grid[space.posx][space.posy]);
						space.posx += 1;
					}
					else
					{
						valid = 0;
					}
				}
				if (input == 'R')
				{
					if (space.posy + 1 < 5)
					{
						swap(grid[space.posx][space.posy + 1], grid[space.posx][space.posy]);
						space.posy += 1;
					}
					else
					{
						valid = 0;
					}
				}
				if (input == 'L')
				{
					if (space.posy - 1 >= 0)
					{
						swap(grid[space.posx][space.posy - 1], grid[space.posx][space.posy]);
						space.posy -= 1;
					}
					else
					{
						valid = 0;
					}
				}
			}
		}
		cin.get();
		if (valid == 0)
		{
			cout << "This puzzle has no final configuration." << endl;
		}
		else
		{
			for (int i = 0; i < 5; ++i)
			{
				for (int j = 0; j < 5; ++j)
				{
					if (j != 4)
						cout << grid[i][j] << ' ';
					else
						cout << grid[i][j];
				}
				cout << endl;
			}
		}
	}
}
相关标签: 算法入门紫