UVa 227 Puzzle(习题3-5)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/decision2016/article/details/54627545

这题用了不少的时间,反正就是模拟吧,最主要的地方就是字符串获取以及一些细节的地方,有的地方一不注意就会出问题

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

char map[6][6];
int a[4][2]={{-1,0},{1,0},{0,-1},{0,1}};  //简化代码 
int x,y,cnt = 0;
		
bool order(char c)           //执行命令 
{
	int now,nowx,nowy;
	char tmp = ' ';
	if(c=='A') now = 0;
	else if(c=='B') now = 1;
	else if(c=='L') now = 2;
	else if(c=='R') now = 3;
	else return 0;
	nowx = x + a[now][0];
	nowy = y + a[now][1];
	if(nowx<0||nowx>4||nowy<0||nowy>4) return 0;
	else
	{
		map[x][y] = map[nowx][nowy];
		map[nowx][nowy] = ' ';
		x = nowx; y = nowy;
	}
	return true;
}

int main()
{
	//freopen("std.in","r",stdin);
	//freopen("std.out","w",stdout);
	char c;
	while(gets(map[0])) 
	{
		if(map[0][0]=='Z') break;  //获取字符串 
		if(cnt>0) cout<<endl; 
	    int flag = 0,sign = 0;
        for(int i = 1;i<5;i++) gets(map[i]);
        for(int i= 0;i<5;i++)
           for(int j=0;j<5;j++)
              if(map[i][j]>'Z'||map[i][j]<'A'){x=i;y=j;}
		while(1)
		{
			c = getchar();
			if(c=='\n') continue;
			if(c=='0') break;
			if(order(c)) continue;
			else {sign = 1; continue;}
		}
		c = getchar();
		cout<<"Puzzle #"<<++cnt<<":"<<endl;
		if(sign) cout<<"This puzzle has no final configuration."<<endl;
		else
		{
			for(int i = 0;i<5;i++)
			{
			      for(int j = 0;j<4;j++)
			      cout<<map[i][j]<<" ";
			      cout<<map[i][4]<<endl;
			}
		}
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/decision2016/article/details/54627545
今日推荐