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

来源:互联网 发布:土耳其修宪 知乎 编辑:程序博客网 时间:2024/06/04 22:17

链接: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);}elsereturn;}}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;elsecout << "NO" << endl;return 0;} 


0 0
原创粉丝点击