codeforces 242C map记录+BFS
2014-03-20 23:29
316 查看
/* 题意:一个棋盘有的点可以走,有的点不能走,求从起点到终点最少要多少 步,假如无法走到则输出-1. 思路:普通的暴力BFS,由于图是10^9*10^9,所以要用到map来记录图。 */ #include <cstdio> #include <map> #include <queue> using namespace std; int main(void) { int x0,y0,x1,y1,n,r,a,b; map<int,map<int,int>>m; while (scanf("%d%d%d%d%d",&x0,&y0,&x1,&y1,&n) == 5) { while (n--) { scanf("%d%d%d",&r,&a,&b); for(int i=a; i<=b; i++) m[r][i] = -1; } queue<int>q; q.push(x0); q.push(y0); q.push(0); int ans = -1;//无法走通则ans为-1 while (!q.empty())//BFS { int x = q.front(); q.pop(); int y = q.front(); q.pop(); int step = q.front(); q.pop(); if (x==x1 && y==y1) { ans = step;//step记录到该点需走多少步 break; } for(int i=-1; i<=1; i++) for(int j=-1; j<=1; j++) { if (i==0 && j==0) continue; int cx = x+i; int cy = y+j; if (m[cx][cy] == -1) { m[cx][cy] = 1; q.push(cx); q.push(cy); q.push(step+1); } } } printf("%d\n",ans); } return 0; }
相关文章推荐
- SDUTOJ 3058 路线冲突问题 ——bfs记录路径
- Codeforces 301_div.2_Ice Cave(BFS走冰块)
- poj-3414-Pots【BFS+记录路径】
- Codeforces 540C Ice Cave (BFS)
- codeforces 793B - Igor and his way to work(bfs)
- poj 3414 bfs+记录路劲
- codeforces 590C(bfs)
- POJ3984 迷宫问题(深搜DFS+广搜BFS)搜索记录坐标,坑
- Codeforces 190E Counter Attack【思维+Bfs】好题!
- Codeforces 225D Snake 位运算hash + bfs
- HDU 1026 Ignatius and the Princess I && BFS+记录路径
- codeforces 788C The Great Mixing( BFS / dp+bitset优化 )
- Codeforces 225D Snake(状压BFS)
- Codeforces 520B. Two Buttons(隐式BFS)
- Codeforces 689B Mike and Shortcuts DFS or BFS
- poj Pots(BFS)(路径记录)(模拟)
- HDU1026 Ignatius and the Princess I 【BFS】+【路径记录】
- codeforces 793B - Igor and his way to work(bfs)
- CodeForces-540C//Codeforces Round #301 (Div. 2)C BFS
- Codeforces 677D Vanya and Treasure 暴力+BFS