poj1573

//poj1573 和poj2632一样,又是机器人路径规划 模拟法+递归 
//给定机器人开始点,根据格子的指令行走,输出走出格子需要的步数 或者输出循环的详细信息 
#include <iostream>
#include <string>
using namespace std;
char ins[15][15];
int mark[15][15]; 
int step[15][15];
bool deadCircle = false;
int deadX;
int deadY; 
int deal(int row, int col, int xpos, int ypos)
{
	if(xpos < 0 || xpos >= row || ypos < 0 || ypos >= col)
		return 0; 
	if(mark[xpos][ypos] == 1) // 死循环了
	{
		deadCircle = true;
		deadX = xpos;
		deadY = ypos;
		return 0;
	}
	mark[xpos][ypos] = 1; 	//标记已经访问
	//跳转到下一格 
	int xtemp = xpos;
	int ytemp = ypos;
	switch(ins[xpos][ypos])
	{
	case 0:
		ypos--;
		break;
	case 1:
		xpos++;
		break;
	case 2:
		ypos++;
		break;
	case 3:
		xpos--;
		break;
	}
	if(mark[xpos][ypos] != 1)
		step[xpos][ypos] = step[xtemp][ytemp] + 1;		//标记从起点走到这里已经用了多少步 
	return 1+deal(row, col,  xpos, ypos);
}
int main()
{
	int row, col, come;
	cin>>row>>col>>come;
	while(row || col || come)
	{
		memset(ins, 0, sizeof(ins));
		memset(mark, 0, sizeof(mark));
		memset(step, 0, sizeof(step));
		deadX = -1;
		deadY = -1;; 
		deadCircle = false;
		for(int i = 0; i < row; i++)
		{
			for(int j = 0; j < col; j++)
			{
				char c;
				cin>>c;
				switch(c)
				{
				case 'W':
					ins[i][j] = 0;
					break;
				case 'S':
					ins[i][j] = 1;
					break;
				case 'E':
					ins[i][j] = 2;
					break;
				case 'N':
					ins[i][j] = 3;
					break;
				}
			}
		}	
		int xpos = 0;
		int ypos = come - 1;
		int steps = deal(row, col, xpos, ypos);
		if(!deadCircle)
		{
			cout<<steps<<" step(s) to exit"<<endl;
		}
		else
		{
			cout<<step[deadX][deadY]<<" step(s) before a loop of "<<steps - step[deadX][deadY]<<" step(s)"<<endl;
		}
		cin>>row>>col>>come;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值