Puzzle UVA - 227

这道题...输出格式令人好无语,用c写不下去了,一直AW,心态爆炸改用c++重写,改了贼多次,终于搞定

#include <iostream>
#include <string>

using namespace std;

string strs[5];
int x, y;  // 记录空格的坐标
int first = 1;  // 判断是否为第一个输出
int kcase = 1;  // 判断操作次数
int flag = 1;  // 判断操作是否非法

int input();
int output();

int main() {
	while (true) {
		input();
		if (strs[0][0] == 'Z')
			return 0;
		output();
	}
	return 0;
}

int input() {
	char c;
	for (int i = 0; i < 5 ; i++) {  // 输入5行数据
		getline(cin, strs[i]);
		if (strs[0][0] == 'Z')  // 若第一个字符是Z则退出
			return 0;
	}
	
	for (int i = 0; i < 5 ; i++)  // 记录空格的位置
		for (int j = 0; j < 5; j++)
			if (strs[i][j] == ' ') {
				x = i; y = j;
			}

	flag = 1;
	while ((c = getchar()) != '0') {
		if (flag && c == 'A') {
			if (x > 0) {
				strs[x][y] = strs[x-1][y];
				strs[x-1][y] = ' ';
				x -= 1;
			}
			else
				flag = 0;
		}
		else if (flag && c == 'B') {
			if (x < 4) {
				strs[x][y] = strs[x+1][y];
				strs[x+1][y] = ' ';
				x += 1;
			}
			else
				flag = 0;
		}
		else if (flag && c == 'L') {
			if (y > 0) {
				strs[x][y] = strs[x][y-1];
				strs[x][y-1] = ' ';
				y -= 1;
			}
			else
				flag = 0;
		}
		else if (flag && c == 'R') {
			if (y < 4) {
				strs[x][y] = strs[x][y+1];
				strs[x][y+1] = ' ';
				y += 1;
			}
			else
				flag = 0;
		}
		else if (flag && c != '\n')
			flag = 0;
		else
			continue;
	}
	cin.get();  // 接收换行符

	return 0;
}

int output() {
	if (first)
		first = 0;
	else
		putchar('\n');
	cout << "Puzzle #" << kcase++ << ':' << endl;
	if (flag == 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 << strs[i][j];
				else
					cout << strs[i][j] << ' ';
			}
			cout << endl;
		}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/malazhuzai/article/details/83514388