Uva1600——Patrol Robot
2016-03-05 17:47
375 查看
这题:找最短路径,只是可以跨越障碍,不能连续跨越K个障碍。
可以通过BFS做。
一开始我没有用vis数组,是在输入的矩阵中操作的,结果一直WR,不明白,为毛加了vis就可以,同样是标记的,自己还是有待提高。
下面AC代码:
可以通过BFS做。
一开始我没有用vis数组,是在输入的矩阵中操作的,结果一直WR,不明白,为毛加了vis就可以,同样是标记的,自己还是有待提高。
下面AC代码:
#include <iostream> #include <queue> #include <cstring> using namespace std; struct node { int x, y, count, sum; //xy为坐标,count为走了多少步,sum为连续跨越几个障碍了。 }; int xy[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}}; int num[25][25]; int n, m, k; bool vis[25][25][25]; int bfs(int x1, int y1, int x2, int y2) { node no; no.x = x1; no.y = y1; no.count = 0; /* if(num[x1][y1] == 1) //起点是1,看作已经跨越障碍了,不需要障碍数 + 1. no.sum = 1; else*/ no.sum = 0; queue<node> Q; Q.push(no); memset(vis, 0, sizeof(vis)); vis[0][0][0] = true; // num[x1][y1] = -1; while(!Q.empty()) { node nod = Q.front(); Q.pop(); if(nod.x == x2 && nod.y == y2) return nod.count; for(int i = 0; i < 4; i++) { int x = nod.x + xy[i][0], y = nod.y + xy[i][1], z = nod.count, s = nod.sum; if(!(x >= 0 && x < n && y >= 0 && y < m)) continue; if(num[x][y]) s++; else s = 0; if(s > k || vis[x][y][s]) continue; vis[x][y][s] = true; no.x = x; no.y = y; no.count = z + 1; no.sum = s; Q.push(no); } } return -1; } int main() { freopen("1.txt", "r", stdin); int t; cin >> t; while(t--) { cin >> n >> m; cin >> k; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) cin >> num[i][j]; int x1 = 0, y1 = 0, x2 = n - 1, y2 = m - 1; cout << bfs(x1, y1, x2, y2) << endl; } return 0; }
相关文章推荐
- 接口抽象类
- 第二次作业 黎娜 2013551605
- 分页代码
- 面试常客Handler详细解析(HandlerThread是什么)(四)
- Docker实践之自定义镜像、推送至远程docker hub
- 单例模式写法
- performSelectorOnMainThread:withObject: waitUntilDone 参数解释
- Python IDLE或Python Shell不支持中文编码的解决方案
- 编程学习第二天,初识Python
- jquery高版本去除了 live的用法,用on代替
- 瀑布流
- 创建索引表
- 仿QQ实现从底部滑出选择框
- alarm and pause Functions
- DomainModel接收参数
- LeetCode : Regular Expression Matching [java]
- python 小练习之山寨版markdown格式txt文件转html文件
- Android多点触控基础
- 连连看完善
- leetcode:122. Best Time to Buy and Sell Stock II(java)解答