P2298 Mzc和男家丁的游戏
题目链接
题目思路
依旧是bfs,记得这个有 无答案 情况
题目代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 2010;
char g[N][N];
int dist[N][N];
bool st[N][N];
int n, m;
int bfs(int x, int y)
{
memset(dist, -1, sizeof dist);
queue<PII> q;
q.push({x, y});
dist[x][y] = 0;
st[x][y] = true;
while(q.size())
{
auto t = q.front();
q.pop();
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
for(int i = 0; i < 4; i ++ )
{
int a = t.first + dx[i], b = t.second + dy[i];
if(a >= 0 && a < n && b >= 0 && b < m && g[a][b] != '#' && !st[a][b])
{
dist[a][b] = dist[t.first][t.second] + 1;
st[a][b] = true;
if(g[a][b] == 'd')
{
return dist[a][b];
}
q.push({a, b});
}
}
}
return -1;
}
int main()
{
memset(g, '#', sizeof g);
cin >> n >> m;
for(int i = 0; i < n; i ++ ) cin >> g[i];
int x, y;
for(int i = 0; i < n; i ++ )
{
for(int j = 0; j < m; j ++ )
if(g[i][j] == 'm')
x = i, y = j;
}
int t = bfs(x, y);
if(t == -1) cout << "No Way!" << endl;
else cout << t << endl;
return 0;
}
孤独本是常态

浙公网安备 33010602011771号