Tinkoff B. Igor and his way to work(BFS)

链接:http://codeforces.com/contest/793/problem/B

题目大意,你有一个起点有一个终点,你要从起点到终点去,但是你转弯的次数不可以大于2次。问是否可以到达。

解法:BFS找到一个方向直接把这个方向一直走走到不能走为止,所有点压入进去,并且记录一下转弯次数,大于2则退出。

代码如下:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1005; 
char G[maxn][maxn];
int d[4][2] = {-1,0,0,1,1,0,0,-1};
int sx, sy, ex, ey, n, m, cnt[maxn][maxn];
bool vst[maxn][maxn];

struct node
{
	int step;
	int x, y;
};

queue <node> q;

bool Check(int x, int y, int step)
{
	if(x >= 0 && x < n && y >= 0 && y < m && G[x][y] != '*' && ((!vst[x][y]) || (cnt[x][y] >= step)))
		return 1;
	return 0;
}

void add(int x, int y, int dir, int step)
{
	node tmp;
	while(1)
	{
//		cout << x << " " << y << " " << step << endl;
		x += d[dir][0];
		y += d[dir][1];
		if(Check(x, y, step))
		{
			vst[x][y] = 1;
			tmp.x = x;
			tmp.y = y;
			tmp.step = step;
			cnt[x][y] = step; 
			q.push(tmp);
		}
		else
			return;
	}
}

bool bfs()
{
	node now, next;
	vst[sx][sy] = 1;
	for(int i = 0; i < 4; i++)
		add(sx, sy, i, 0);
	while(!q.empty())
	{
		now = q.front();
		q.pop();
		if(now.step > 2)
			return 0;
//		cout << now.x << " " << now.y << " " << now.step << endl;
		if(now.x == ex && now.y == ey)
			return 1;
		next.step = now.step + 1;
		for(int i = 0; i < 4; i++)
		{
			next.x = now.x + d[i][0];
			next.y = now.y + d[i][1];
			if(Check(next.x, next.y, next.step))
				add(now.x, now.y, i, next.step);
		}
	}
	return 0;
}

int main()
{
//	ios::sync_with_stdio(false); 
	memset(vst, 0, sizeof(vst));
	memset(cnt, 0, sizeof(cnt));
	scanf("%d%d", &n, &m);
	for(int i = 0; i < n; i++)
	{
		scanf("%s", &G[i]);
		for(int j = 0; j < m; j++)
			if(G[i][j] == 'S')
			{
				sx = i;
				sy = j;
			}
			else if(G[i][j] == 'T')
			{
				ex = i;
				ey = j;	
			}
	}
	if(bfs())
		cout << "YES" << endl;
	else
		cout << "NO" << endl;
	return 0;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值