UVA - 10047 The Monocycle (BFS)
2015-07-25 12:19
423 查看
题目大意:有一个n*m的网格,网格上面有的地方有障碍物
现在有一个人,骑着独轮车,要求从一个地方到达另一个地方,骑独轮车时,只能直走,或者左拐,右拐,不能向后走
独轮车的轮子被分成了5部分,每部分都有对应的颜色,刚开始时是绿色向下,当经过一个格子时,颜色就会变换
问从起点出发到终点,到终点时独轮车的绿色颜色向下,需要多久
解题思路:暴力BFS
现在有一个人,骑着独轮车,要求从一个地方到达另一个地方,骑独轮车时,只能直走,或者左拐,右拐,不能向后走
独轮车的轮子被分成了5部分,每部分都有对应的颜色,刚开始时是绿色向下,当经过一个格子时,颜色就会变换
问从起点出发到终点,到终点时独轮车的绿色颜色向下,需要多久
解题思路:暴力BFS
[code]#include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; #define N 30 struct Node{ int x, y, dir, time, color; }start; int dir[4][2] = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}}; int g , vis [5][4]; char str ; int end_x, end_y, n, m; void init() { for (int i = 0; i < n; i++) { scanf("%s", str); for (int j = 0; j < m; j++) { if (str[j] == '#') { g[i][j] = 1; } else { g[i][j] = 0; if (str[j] == 'S') { start.x = i; start.y = j; } if (str[j] == 'T') { end_x = i; end_y = j; } } } } memset(vis, 0, sizeof(vis)); } void solve() { queue<Node> q; start.color = 0; start.time = 0; start.dir = 0; q.push(start); vis[start.x][start.y][0][0] = 1; while (!q.empty()) { Node t = q.front(); q.pop(); if (t.x == end_x && t.y == end_y && t.color == 0) { printf("minimum time = %d sec\n", t.time); return ; } for (int i = 0; i < 4; i++) { if (t.dir + i == 3) continue; Node tt; tt.x = t.x; tt.y = t.y; tt.color = t.color; tt.time = t.time + 1; tt.dir = t.dir; if(tt.dir == i) { tt.x += dir[tt.dir][0]; tt.y += dir[tt.dir][1]; tt.color = (tt.color + 1) % 5; if(tt.x < 0 || tt.x >= n || tt.y < 0 || tt.y >= m || g[tt.x][tt.y] || vis[tt.x][tt.y][tt.color][tt.dir]) continue; vis[tt.x][tt.y][tt.color][tt.dir] = 1; q.push(tt); } else { tt.dir = i; if(!vis[tt.x][tt.y][tt.color][tt.dir]) { vis[tt.x][tt.y][tt.color][tt.dir] = 1; q.push(tt); } } } } printf("destination not reachable\n"); } int main() { int cas = 1; int flag = 0; while (scanf("%d%d", &n, &m) != EOF && n + m) { if(flag) printf("\n"); else flag = 1; init(); printf("Case #%d\n", cas++); solve(); } return 0; }
相关文章推荐
- 最大子序列和问题之算法优化
- 51单片机j基础C程序架构
- 记录一次剁手的"sudo rm -rf /bin"(误删linux /bin目录)
- [投资理财经验 ] 深圳炒房客8年:几万元投入赚了3000万 过程惊心动魄
- netscreen ns50 命令行删除配置方法
- android 最新 support library
- group分组之后要求统计count问题
- document.createElement()的用法
- 打开excel很慢的解决方法
- Python基于PycURL自动处理cookie的方法
- 一、小按钮和下面板---调试面板
- WORD中插入VISIO图形,打印乱码解决
- COJN 0558 800600带通配符的字符串匹配
- HDU 5305 Friends
- h323
- 如何恢复、打开、开启默认共享ipc$ c$ Dameware安装出错
- 【YII2学习笔记】20150725-1
- web自学
- Drupal 7 安装时的数据库问题
- 微信支付商户发放现金红包操作说明