CSUOJ 1259 跳跳
2014-08-01 09:31
393 查看
Description
一个每块地板标记着0~9某个数字的迷宫,其中标记1的地板不可以走,标记2~9的地板可以不花时间地跳到任意相同数字的位置,也可以和标记0的地板一样向前后左右任意方向花1个单位时间移动1的距离。给出起点和终点,求起点到终点的最短时间。Input
每组数据第一行一个n,表示尺寸,2 <= n <= 100。接下来n行每行n个0~9的字符,或S表示起点,E表示终点,S和E的运动规则与0相同。整个地图只有一个S和一个E。Output
每组数据输出一个数,占一行,表示起点到终点可以花费的最短时间。如果无法到达重点,输出"Oh No!"Sample Input
5 0S100 00131 00300 00000 003E0 3 S12 010 10E
Sample Output
4 Oh No! BFS的变形 需要注意的一点事遇到2-9的数字就全部push 相应数字
# include <cstdio> # include <queue> # include <cstring> # define N 105 using namespace std; int n; char g ; char vis ; struct pos{int x, y, d;}; queue <pos> Qst[10]; pos st; //描述相邻点的相对位置 const int dx[] = {0, 0, 1, -1}; const int dy[] = {1, -1, 0, 0}; int bfs() { queue <pos> Q; Q.push(st); //访问标记 vis[st.x][st.y] = 1; while(!Q.empty()){ pos cur = Q.front(); Q.pop(); for(int i = 0; i < 4; ++i){ pos nst; //遍历该店上下左右的点 nst.x = cur.x + dx[i]; nst.y = cur.y + dy[i]; //判断是否还在范围内并且未访问过 if(1 <= nst.x && nst.x <= n && 1 <= nst.y && nst.y <= n && !vis[nst.x][nst.y]){ //访问标记 vis[nst.x][nst.y] = 1; char ch = g[nst.x][nst.y]; //判断是否找到终点 找到返回步数 if(ch == 'E') return cur.d+1; //判断是否遇到阻碍 是的话跳过进入下一次循环 if(ch == '1') continue; //如果是 0 步数加 1 把邻接点压入队列 if(ch == '0') nst.d=cur.d+1, Q.push(nst); //如果是2-9可以“传送”的点 找到与该点数字相同点压入队列 else if ('2' <=ch && ch <= '9'){ pos nnst; while(!Qst[ch-'0'].empty()){ nnst = Qst[ch-'0'].front(); Qst[ch-'0'].pop(); vis[nnst.x][nnst.y] = 1; nnst.d = cur.d + 1; Q.push(nnst); } } } } } return -1; } int main() { while (~scanf("%d", &n)){ pos tmp; //将队列清空 for(int i = 2; i <= 9; i++) while (!Qst[i].empty()) Qst[i].pop(); for (int i = 1; i <= n; i++){ scanf("%s", g[i]+1); memset(vis[i]+1, 0, sizeof(char)*n); for(int j = 1; j <= n; j++){ char ch = g[i][j]; //把可跳跃位置压入队列 if ('2' <= ch && ch <= '9'){ tmp.x = i, tmp.y = j; Qst[ch-'0'].push(tmp); } //记录初始位置 else if (ch == 'S'){ st.x = i, st.y = j; st.d = 0; } } } int ans = bfs(); if (ans == -1) printf("Oh No!\n"); else printf("%d\n", ans); } return 0; }
相关文章推荐
- BFS给力的题目 CSU1259: 跳跳
- CSU 1259 跳跳 (bfs)
- CSU 1259 跳跳
- Stock Wave+csuoj+简单dp
- CSUOJ 2031 Barareh on Fire
- csuoj 1559 外卖的撕‘哔’大战
- CSUOJ 1531 Jewelry Exhibition
- csu oj Infected Computer 1427
- CSUOJ 1248 非变性聚丙烯酰胺凝胶电泳
- [CSUOJ1808] 地铁(dijkstra,堆,边最短路)
- Central Avenue Road+csuoj+水题
- CSUOJ 1726 你经历过绝望吗?两次!BFS+优先队列
- CSUOJ1238--兵临城下
- CSUOJ 1637 Yet Satisfiability Again!
- CSUOJ:K swap operation
- CSUOJ 1008 Horcrux
- CSUOJ 1150-食用油
- CSUOJ 1116 Kingdoms
- 湖南省第十二届大学生程序设计竞赛A题 2016 (csuoj1803)
- csuoj 1339 最后一滴血