Robot Motion POJ - 1573

题意是 一个小人 从上边界进入 如果能离开 就输出出步数

如果不能离开 输出从哪开始循环和循环的步数

要说的都在代码里面了

#include<iostream>
#include<cstring>
#include<cstdio>
#define clr(a,b) memset(a,b,sizeof(a));
using namespace std;
char g[11][11];
int visit[11][11];
int stepa[11][11];//记录走到此位置时的步数。因为方向已被固定加上有visit数组标记 所以最坏情况就是整个数组被标一边而已
int n,m,in,startx,starty,step;

void dfs(int x,int y)
{
	step++;
	//cout<<step<<'\t';
	if(x<0||x>=n||y<0||y>=m)//走到了边界
	{
		cout<<step<<" step(s) to exit"<<endl;
		return;
	}
	if(visit[x][y])//走的时候遇到了走过的位置 说明出现了环
	{
		cout<<stepa[x][y]<<" step(s) before a loop of "<<step-stepa[x][y]<<" step(s)"<<endl;
		return;
	}
	stepa[x][y]=step;
	visit[x][y]=true;
	int lx=x;
	int ly=y;
	if(g[x][y]=='N')
	{
		lx-=1;
		//cout<<'n';
	}
	if(g[x][y]=='S')
	{
		lx+=1;
		//cout<<'s';
	}
	if(g[x][y]=='E')
	{
		ly+=1;
		//cout<<'e';
	}
	if(g[x][y]=='W')
	{
		ly-=1;
		//cout<<'w';
	}
	dfs(lx,ly);
}

int main()
{
	while(cin>>n>>m>>in)
	{
		if(!n&&!m&&!in) break;
		clr(visit,0)
		clr(stepa,0)
		startx=0;
		starty=in-1;//图是从零开始的 所以坐标位要减1 wa了一发
		step=-1;
		//visit[startx][starty]=1;
		for(int i=0;i<n;i++)
		{
			scanf("%s",g[i]);
		}
		dfs(startx,starty);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41544329/article/details/82455330