Find a way
题目
样例
这道题主要用了bfs的搜索方法,把所有的路都走一遍,然后把用的时间记录下来,最后比较大小,然后把最少的时间乘以11输出
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <sstream>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
int T, n, m;
char mp[1005][1005];//原始地图
int vis[1005][1005];//记录人是否走过
int ytime[1005][1005];//Y 经过这个地方的时间
int mtime[1005][1005];//M 经过这个地方的时间
int dt[][2] = { {1,0},{-1,0},{0,1},{0,-1} };//四个方向
struct node
{
int x, y;//坐标
};
node now, net;
node Y, M;
void bfs(int f)//人
{
queue<node>q;
memset(vis, 0,sizeof(vis));//都要初始化,都没走过,设为0
if (f == 0)// Y的情况
{
memset(ytime, INF,sizeof(ytime));
q.push(Y);
vis[Y.x][Y.y] = 1;
ytime[Y.x][Y.y] = 0;
}
if (f == 1)// M的情况
{
memset(mtime, INF,sizeof(mtime));
q.push(M);
vis[M.x][M.y] = 1;
mtime[M.x][M.y] = 0;
}
while (!q.empty())// bfs 一样的套路
{
now = q.front();
q.pop();
for (int i = 0; i < 4; i++)//四个方向
{
net.x = now.x + dt[i][0];
net.y = now.y + dt[i][1];
if (net.x >= 0 && net.x < n && net.y >= 0 && net.y < m && !vis[net.x][net.y] && mp[net.x][net.y] != '#')//满足条件
{
q.push(net);//入队
vis[net.x][net.y] = 1;//走过了
if (f == 0)//Y 的路线时间
ytime[net.x][net.y] = ytime[now.x][now.y] + 1;
if (f == 1)//M 的路线时间
mtime[net.x][net.y] = mtime[now.x][now.y] + 1;
}
}
}
}
int main()
{
while (cin >> n >> m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> mp[i][j];
if (mp[i][j] == 'Y')
{
Y.x = i;
Y.y = j;
}
if (mp[i][j] == 'M')
{
M.x = i;
M.y = j;
}
}
}
bfs(0); //Y的路线
bfs(1); //M的路线
int ans = INF; //最小步数
for (int i = 0; i < n; i++)//搜一遍地图,看一下"@"所在地方的时间之和,取最小值
for (int j = 0; j < m; j++)
if (mp[i][j] == '@')
ans = min(ans, ytime[i][j] + mtime[i][j]);
cout << 11 * ans << endl;
}
return 0;
}