hhhhhh
2024-09-22 16:59:47
发布于:上海
13阅读
0回复
0点赞
#include<queue>
using namespace std;
const int N = 1010;
struct node{
int x;
int y;
int step;
};
int n, m, xx, yy;
node mp[N][N];
queue<node> q;
queue<int> g;
char ma[N][N];
bool flag, vip[N][N];
int main(){
cin >> n >> m;
for (int i = 1;i <= n;i ++){
for (int j = 1;j <= m;j ++){
cin >> ma[i][j];
mp[i][j].x = i;
mp[i][j].y = j;
if (ma[i][j] == '2'){
mp[i][j].step = 0;
q.push(mp[i][j]);
}
}
}
vip[xx][yy] = 1;
g.push(mp[xx][yy].step);
while(q.size()){
node k = q.front();
q.pop();
if (k.x - 1 > 0 && k.x <= n && !vip[k.x - 1][k.y] && ma[k.x - 1][k.y] == '1'){
node v = k;
v.x -= 1;
v.step += 1;
g.push(v.step);
g.pop();
vip[v.x][v.y] = 1;
ma[v.x][v.y] = '2';
q.push(v);
}
if (k.x + 1 <= n && k.x > 0 && !vip[k.x + 1][k.y] && ma[k.x + 1][k.y] == '1'){
node v = k;
v.x += 1;
v.step += 1;
g.push(v.step);
g.pop();
vip[v.x][v.y] = 1;
ma[v.x][v.y] = '2';
q.push(v);
}
if (k.y - 1 > 0 && k.y <= m && !vip[k.x][k.y - 1] && ma[k.x][k.y - 1] == '1'){
node v = k;
v.y -= 1;
v.step += 1;
g.push(v.step);
g.pop();
vip[v.x][v.y] = 1;
ma[v.x][v.y] = '2';
q.push(v);
}
if (k.y > 0 && k.y + 1 <= m && !vip[k.x][k.y + 1] && ma[k.x][k.y + 1] == '1'){
node v = k;
v.y += 1;
v.step += 1;
g.push(v.step);
g.pop();
vip[v.x][v.y] = 1;
ma[v.x][v.y] = '2';
q.push(v);
}
}
for (int i = 1;i <= n;i ++){
for (int j = 1;j <= m;j ++){
if (ma[i][j] == '1'){
flag = 1;
}
}
}
if (!flag) cout << g.front();
else cout << -1;
return 0;
}
这里空空如也
有帮助,赞一个