UVA227 Puzzle(C++)

(1) 输出的时候注意相邻两个案例之间要有空行

(2) 输出的字符不要包含中文标点

  • 代码
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, char *argv[])
{
	int puzzleNum = 1; //计数 
	string operate; //存储具体操作 (ABLR) 
	while(1)
	{
		string str[5];
		/* 1. 数据预处理 */ 
		getline(cin, str[0]);
		if(str[0] == "Z") break;
		if(puzzleNum != 1) cout<<endl; 
		for(int i = 1; i < 5; i++) getline(cin, str[i]);
		string s;
		operate = "";
		while(1)
		{
			getline(cin, s); 
			operate += s;
			if(s[s.length()-1] == '0') break;
		}
		
		/* 2. 找出空格位置 */ 
		int x,y; //空格的位置
		for(int i = 0; i < 5; i++)
			for(int j = 0; j < 5; j++)
			{
				if(str[i][j] == ' ')
				{
					x = i;
					y = j;
					goto L;
				}
			}
		L:
		
		/* 3. 模拟操作 */
		bool b = 1; //判断最终有没有成功
		int xx, yy;
		for(int i = 0; i < operate.length()-1; i++)
		{
			xx = x; yy = y; //存储该步操作之前的位置 
			
			if(operate[i] == 'A') x--;
			if(operate[i] == 'B') x++;
			if(operate[i] == 'L') y--;
			if(operate[i] == 'R') y++;
			
			// 判断操作合法性
			if(x == -1 || y == -1 || x == 5 || y == 5)
			{
				b = 0;
				break;
			}
			
			// 执行操作步骤
			str[xx][yy] = str[x][y];
			str[x][y] = ' ';
		} 
		
		/* 4. 输出 */ 
		cout<<"Puzzle #"<<puzzleNum++<<":"<<endl;
		if(b)
		{
			for(int i = 0; i < 5; i++)
				cout<<str[i][0]<<" "<<str[i][1]<<" "<<str[i][2]<<" "<<str[i][3]<<" "<<str[i][4]<<endl;
		}
		else
			cout<<"This puzzle has no final configuration."<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cxzs110/article/details/88528976