1. 程式人生 > >Puzzle UVA - 227

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;
}