BFS--cf793b Igor and his way to work
来源:互联网 发布:java最新书籍 编辑:程序博客网 时间:2024/05/29 17:38
从起点走到终点,最多只能转2次弯,求是否能到达终点。
如果用dfs,会因为重复状态过多超时。
所以需要bfs,并且记录是否访问过。
由于有方向和转弯次数的限制,所以需要一起在vis中记录。
#include <iostream>
#include <cstdio>
#include <queue>
using namespacestd;
const int maxn =1000 + 5;
char mp[maxn][maxn];
const int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
struct point {
int x,y;
}s,t;
struct node{
int x,y;
int d,turn;//剩余的转弯次数
};
bool succ = false;
int vis[maxn][maxn][4][3];//x y dir turn
int n,m;
void bfs()
{
queue<node> q;
int tx,ty;
for (int i =0; i < 4; i ++) {
tx = s.x +dir[i][0];
ty = s.y +dir[i][1];
if(tx >=0 && ty >= 0 && tx <n && ty < m &&mp[tx][ty] != '*'){
q.push({tx,ty,i,2});
vis[tx][ty][i][2] =1;}
}
while (!q.empty()) {
node tmp = q.front();q.pop();
if(tmp.x ==t.x && tmp.y ==t.y) {succ =true;break;}
for (int i =0; i < 4; i ++) {
int tx = tmp.x +dir[i][0];
int ty = tmp.y +dir[i][1];
if(tx >=0 && ty >= 0 && tx <n && ty < m &&mp[tx][ty] != '*'){
if(i == tmp.d)
{
if(!vis[tx][ty][i][tmp.turn]){
vis[tx][ty][i][tmp.turn] =1;
q.push({tx,ty,i,tmp.turn});
}
}
else{
if(tmp.turn >0)
{
if(!vis[tx][ty][i][tmp.turn -1]){
vis[tx][ty][i][tmp.turn -1] = 1;
q.push({tx,ty,i,tmp.turn -1});
}
}
}
}
}
}
}
int main()
{
scanf("%d%d",&n,&m);
getchar();
for (int i =0; i < n; i ++) {
for (int j =0; j < m; j ++) {
scanf("%c",&mp[i][j]);
if(mp[i][j] =='S') {s.x = i,s.y = j;}
elseif (mp[i][j] =='T') {t.x = i,t.y = j;}
}
getchar();
}
bfs();
if(succ)printf("YES\n");
else printf("NO\n");
return0;
}
- BFS--cf793b Igor and his way to work
- CF793B:B Igor and his way to work(DFS & BFS)
- Tinkoff B. Igor and his way to work(BFS)
- Igor and his way to work-Codeforce 793B BFS
- B. Igor and his way to work
- codeforces Igor and his way to work
- B. Igor and his way to work
- B. Igor and his way to work
- Codeforces 793B Igor and his way to work (dfs/bfs
- codeforces B. Igor and his way to work dfs or bfs
- Codeforces-739B:Igor and his way to work(BFS+优化)
- codeforce 793 B Igor and his way to work
- Codeforces 793B Igor and his way to work 题解
- Codeforces 793B Igor and his way to work dfs
- CF-Tinkoff Challenge-Elimination Round-B-Igor and his way to work
- Codeforces 793b B. Igor and his way to work 觉得大神写的3维bfs太复杂,突然发现这题是连连看算法。
- and that led to his
- Way to Innovation, Start here and now!
- 购物车系列_控制器
- LCP协商过程
- linux echo命令两个参数-n -e
- eft join 是left outer join的区别
- ROS读取手机GPS数据(1)
- BFS--cf793b Igor and his way to work
- 从内存管理、内存泄漏、内存回收探讨C++内存管理
- 百度编辑器Ueditor简单实用方法
- List判空
- mancher入门-- mancher模板+解释
- 购物车系列_映射文件
- Android开发总结 -- 【持续更新】
- 查找对应jar的maven包(查找对应的jar 或maven)
- 【Android】Animation(二)