牛客练习赛12-B-迷宫
2018-02-11 22:14
295 查看
题目链接:https://www.nowcoder.net/acm/contest/解题思路:最容易想到的肯定是BFS,这里主要考虑两种情况,第一种是直接不需要拿到钥匙就可以到,第二种是需要拿到钥匙然后再去开锁,这里需要注意的是,就算能直接到也需要判断那种方法用到的步数最少。有可能出错的地方是:1,把队列Q开在了全局,这时候需要每bfs一次就把Q清空。2,memset(v,0,sizeeof(v))可以写在bfs里面也可以每bfs一次就执行一次。3,因为迷宫我是从1开始的,所以最后没有边界的判断,如果是从0开始需要加上。
AC代码:
AC代码:
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<queue> #include<algorithm> using namespace std; int h, k; char m[505][505]; int v[505][505]; int t[4][2] = { {-1,0},{1,0},{0,-1},{0,1} }; int dx, dy, ex, ey, sx, sy, kx, ky; int ans; struct Node { int i; int j; int stp; }; Node now; int bfs(int x, int y,int x2,int y2,int stp) { memset(v, 0, sizeof(v)); v[x][y] = 1; now.i = x; now.j = y; now.stp = stp; queue<Node> Q; Q.push(now); while (!Q.empty()) { now = Q.front(); Q.pop(); Node next; if (now.i == x2&&now.j == y2) { return now.stp+1; } for (int i = 0; i < 4; i++) { int x = now.i + t[i][0]; int y = now.j + t[i][1]; if (m[x][y] == '.'&&v[x][y] == 0) { v[x][y] = 1; next.i = x; next.j = y; next.stp = now.stp + 1; Q.push(next); } } } return -1; } int main() { scanf("%d%d", &h, &k); for (int i = 1; i <=h; i++) { scanf("%s", m[i]+1); } for (int i = 1; i <= h; i++) { for (int j = 1; j <= k; j++) { if (m[i][j] == 'S') { sx = i; sy = j; } if (m[i][j] == 'D') { dx = i; dy = j; } if (m[i][j] == 'K') { kx = i; ky = j; } if (m[i][j] == 'E') { ex = i; ey = j; } } } m[sx][sy] = '.'; m[ex][ey] = '.'; m[kx][ky] = '.'; int ans1 = bfs(sx, sy, ex, ey,0); m[kx][ky] = '.'; int ans2 = bfs(sx, sy, kx, ky, 0); m[dx][dy] = '.'; int ans3 = bfs(kx, ky, dx, dy, 0); int ans4 = bfs(dx, dy, ex, ey, 0); if (ans1 == -1) { if (ans2 == -1 || ans3 == -1 || ans4 == -1) { printf("-1\n"); } else { printf("%d\n", ans2 + ans3 + ans4); } } else { ans = min(ans1, ans2 + ans3 + ans4); printf("%d\n", ans); } return 0; }有问题私聊哦~ 么么哒
相关文章推荐
- 牛客练习赛12 B 迷宫 【BFS】
- 牛客练习赛12 B、迷宫
- 牛客练习赛12 B题
- 牛客练习赛12
- 2018/2/9牛客练习赛12 A-圆圆
- 【nowcoder 练习赛12】迷宫(bfs)
- 牛客练习赛12-A-圆圆
- 牛客网练习赛12迷宫(宽搜)
- 4000 牛客练习赛12 B迷宫解题报告
- 牛客练习赛12 B题
- 牛客练习赛12 A 圆圆
- 牛客练习赛12 D 图图 (高斯消元)
- 牛客练习赛12
- 【牛客练习赛12】 A B 【bfs +简单状压】
- [Offer收割]编程练习赛29 题目1 : 逃离迷宫4
- 【[Offer收割]编程练习赛12 D】 寻找最大值
- 牛客练习赛6 B题 点权和
- 牛客练习赛6 D 世界上最可爱的珂朵莉 贪心
- 牛客练习赛6 B 点权和 树点权和
- 牛客练习赛3 F 监视任务 每个区间K个 树状数组+贪心