经典迷宫问题
AC代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 110;
int n, m;
int g[N][N], d[N][N];
typedef pair<int, int> PII;
queue<PII> q;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};//四个方向向量
int bfs()
{
memset(d, -1, sizeof(d));
q.push({0, 0});
d[0][0] = 0;
while(q.size())
{
auto t = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
int x = t.first + dx[i];
int y = t.second + dy[i];
if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1)
{
d[x][y] = d[t.first][t.second] + 1;
q.push({x, y});
}
}
}
return d[n - 1][m - 1];
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> m;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
cin >> g[i][j];
}
}
cout << bfs() << endl;
return 0;
}
水桶传递队列
AC代码:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
char g[10][10];
int d[10][10];
typedef pair<int, int> PII;
queue<PII> q;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
void bfs(int x, int y)
{
memset(d, -1, sizeof d);
q.push({x, y});
d[x][y] = 0;
while(q.size())
{
auto t = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
int m = t.first + dx[i], n = t.second + dy[i];
if(m >= 0 && m < 10 && n >= 0 && n < 10 && d[m][n] == -1 && g[m][n] == '.')
{
q.push({m, n});
d[m][n] = d[t.first][t.second] + 1;
}
else if(m >= 0 && m < 10 && n >= 0 && n < 10 && d[m][n] == -1 && g[m][n] == 'L')
{
d[m][n] = d[t.first][t.second] + 1;
cout << d[m][n] - 1 << endl;
}
}
}
}
int main()
{
int x1, y1, x2, y2;
for(int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++)
{
cin >> g[i][j];
if(g[i][j] == 'B') x1 = i, y1 = j;
else if(g[i][j] == 'L') x2 = i, y2 = j;
}
bfs(x1, y1);
return 0;
}