Puzzle UVA - 227(简单模拟)

题目大概:

给出5*5的网格,网格内有一个格是空的,输入操作,使空格水平或竖直移动一个单位,输出最后的网格,期间可以存在非法操作,输出参考原题: 在这里这里这里

思路:

按照题目要求做即可完成,不过需要注意:
1.非法情况(出界)的处理
2.输入遗留换行符的消去
3.原题Sample Input 行末无空格,可自行加上
4.其余可见注释
以下代码比较水了,没什么技术含量,可做参考

//#include "stdafx.h"
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
using namespace std;
string s[10];
int x, y;
void move (int r, int c) {//移动可作一个函数
	swap(s[x][y], s[x + r][y + c]);
	x += r; y += c;
}

int main() {
	int cp = 0, ch = 0;
	while (getline(cin, s[0]) && s[0] != "Z") {
		for (int i = 1; i < 5; i++) getline(cin, s[i]);

		for (int i = 0; i < 5;i++)
			for (int j = 0; j < 5;j++)
				if (s[i][j] == ' ') { x = i, y = j; break; }
					//找到空格位置
		bool wrong = false;

		while ( (ch = getchar()) && ch !='0' ) {//首先会读到一次遗留换行符
//&&优先级较高,左侧括号不能少,这个卡了我好久  T T```
			if (ch == '\n')  continue;
			else if (ch == 'A' && x - 1>=0) move(-1, 0);
			else if (ch == 'B' && x + 1< 5) move( 1, 0);
			else if (ch == 'L' && y - 1>=0) move( 0,-1);
			else if (ch == 'R' && y + 1< 5) move( 0, 1);
			else wrong = true;//取补集就好啦~

		}getchar();//这个千万不能少

		if (cp) printf("\n");//注意格式哦
		printf("Puzzle #%d:\n", ++cp);
		if (wrong) printf("This puzzle has no final configuration.\n");
		else for (int i = 0; i < 5;i++)
				for (int j = 0; j < 5; j++)
					printf("%c%c", s[i][j], j == 4 ? '\n' : ' ');
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值