一、热身 [Cloned] F - Robot Motion

本文介绍了一种模拟机器人在网格地图上移动的算法。机器人遵循地图上的指令移动,包括上、下、左、右方向。算法通过跟踪机器人路径,判断其是否能离开地图或陷入循环,并输出相应的步数。

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

原题:

 



A robot has been programmed to follow the instructions in its path. Instructions for the next direction the robot is to move are laid down in a grid. The possible instructions are 

N north (up the page) 
S south (down the page) 
E east (to the right on the page) 
W west (to the left on the page) 

For example, suppose the robot starts on the north (top) side of Grid 1 and starts south (down). The path the robot follows is shown. The robot goes through 10 instructions in the grid before leaving the grid. 

Compare what happens in Grid 2: the robot goes through 3 instructions only once, and then starts a loop through 8 instructions, and never exits. 

You are to write a program that determines how long it takes a robot to get out of the grid or how the robot loops around. 

题意:

模拟题,输入一张地图,四个字母分别代表上下左右(东西南北),机器人从第一行某一个位置进入,然后进入哪个格子就按照那个格子进行移动,如果能离开地图就输出要走多少步,如果不能离开地图输出要走多少步进入循环和循环多少步

题解:

就是一个比较简单的模拟题,额外加一个数组记录是否走过,然后设置一个标记来记录会不会回到曾经走到过的地方,如果回到了走过的地方,那就记录下到目前为止走了n步,然后再从头走一遍一直走到这个点,记录走了m步,那么也就是要循环n-m步,如果没有到走过地方就离开了地图,那就直接输出n

代码:(AC)

#include<iostream>
#include<cstring>
using namespace std;
char map[500][500];
int visited[500][500];
int main()
{
	int line,row,first;
	while(cin>>line>>row>>first)
	{
		if(line+row+first==0)
			break;
		else
		{
			int i,j;
			for(i=0;i<line;i++)
			{
				for(j=0;j<row;j++)
					visited[i][j]=0;
			}
			for(i=0;i<line;i++)
			{
				for(j=0;j<row;j++)
					cin>>map[i][j];
			}
			int xposition=first-1;
			int yposition=0;
			int step=0;
			int flag=0;
			int notloop=0;
			while(xposition>=0&&yposition>=0&&xposition<row&&yposition<line)
			{
				if(!visited[yposition][xposition])
				{
					visited[yposition][xposition]=1;
					step++;
					if(map[yposition][xposition]=='W')
						xposition--;
					else if(map[yposition][xposition]=='E')
						xposition++;
					else if(map[yposition][xposition]=='S')
						yposition++;
					else 
						yposition--;
				}
				else
				{
					visited[yposition][xposition]=0;
					flag=1;
					break;
				}
			}
				if(flag)
				{
					xposition=first-1;
					yposition=0;
					while(visited[yposition][xposition])
					{
						notloop++;
					if(map[yposition][xposition]=='W')
						xposition--;
					else if(map[yposition][xposition]=='E')
						xposition++;
					else if(map[yposition][xposition]=='S')
						yposition++;
					else 
						yposition--;
					}
					cout<<notloop<<" step(s) before a loop of "<<step-notloop<<" step(s)"<<endl;
				}
				else
					cout<<step<<" step(s) to exit"<<endl;
			}
	}
			return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值