UVA227 Puzzle(C++)

本文介绍了一种基于字符输入的迷宫游戏解谜算法,通过解析特定的操作指令(如ABLR),在二维迷宫中寻找正确的路径。文章详细解释了如何定位空格,模拟操作并检查每一步的合法性,最终输出迷宫的最终状态或失败信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值