#include<bits/stdc++.h>
using namespace std;
int n = 10;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
char c[15][15];
string s[15];
bool vis[15][15];
struct node{
int x;
int y;
int step;
};
queue<node> q;
void BFS(){
while(!q.empty()){
int x = q.front().x;
int y = q.front().y;
int step = q.front().step;
q.pop();
if(c[x][y]=='B'){
cout << step;
return;
}
vis[x][y] = 1;
for (int i = 0; i < 4;i++){
int curx = x + dx[i];
int cury = y + dy[i];
if(c[curx][cury]!='R'&&vis[curx][cury]==0&&curx>=1&&cury>=1&&curx<=n&&cury<=n){
q.push(node{curx, cury, step + 1});
}
}
}
}
int main(){
for (int i = 1; i <= n;i++){
cin >> s[i];
}
for (int i = 1; i <= n;i++){
for (int j = 1; j <= n;j++){
c[i][j] = s[i][j - 1];
if(c[i][j]=='L'){
q.push(node{i, j, -1});
}
}
}
BFS();
return 0;
}
D3443 【提高】走出迷宫的最短路径
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int mn = 155;
int n, m;
int g[mn][mn];
int a, b, c, d;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
struct nd {
int x;
int y;
int p[mn * mn][2];
int l;
};
bool v[mn][mn];
void e() {
queue<nd> q;
nd s;
s.x = a;
s.y = b;
s.l = 1;
s.p[0][0] = a;
s.p[0][1] = b;
v[a][b] = true;
q.push(s);
while (!q.empty()) {
nd f = q.front();
q.pop();
int x = f.x;
int y = f.y;
if (x == c && y == d) {
for (int i = 0; i < f.l; ++i) {
if (i != 0) cout << "->";
cout << "(" << f.p[i][0] + 1 << "," << f.p[i][1] + 1 << ")";
}
cout << endl;
return;
}
for (int i = 0; i < 4; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && g[nx][ny] == 0 && !v[nx][ny]) {
v[nx][ny] = true;
nd t;
t.x = nx;
t.y = ny;
t.l = f.l + 1;
for (int j = 0; j < f.l; ++j) {
t.p[j][0] = f.p[j][0];
t.p[j][1] = f.p[j][1];
}
t.p[f.l][0] = nx;
t.p[f.l][1] = ny;
q.push(t);
}
}
}
cout << "no way" << endl;
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
cin >> g[i][j];
cin >> a >> b;
cin >> c >> d;
a -= 1;
b -= 1;
c -= 1;
d -= 1;
e();
return 0;
}