您的位置:首页 > 其它

牛客练习赛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代码:
#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;
}
有问题私聊哦~ 么么哒
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  牛客练习 B