y6hz @ 2023-09-10 21:41:15
#include<iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> pii;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int dis[1010][1010];
int n, x, y, x2, y2;
char mp[1010][1010];
queue<pii>q;
int bfs(int x, int y) {
memset(dis, -1, sizeof dis);
q.push({x, y});
dis[x][y] = 0;
while (!q.empty()) {
pii f = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int xx = f.first, yy = f.second;
xx += dx[i];
yy += dy[i];
if (xx < 1 || xx > n || yy < 1 || yy > n)
continue;
if (mp[xx][yy] != '0')
continue;
if (dis[xx][yy] > -1)
continue;
q.push({xx, yy});
dis[xx][yy] = dis[f.first][f.second] + 1;
if (dis[x2][y2] > 0)
return dis[x2][y2];
}
}
return -1;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; ++i) {
scanf("%s", mp[i] + 1);
}
cin >> x >> y >> x2 >> y2;
int result = bfs(x, y);
cout << result;
return 0;
}
by y6hz @ 2023-09-10 21:44:30
改了一下,MLE了
#include<iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> pii;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int dis[10000][10000];
int n, x, y, x2, y2;
char mp[10000][10000];
queue<pii>q;
int bfs(int x, int y) {
memset(dis, -1, sizeof dis);
q.push({x, y});
dis[x][y] = 0;
while (!q.empty()) {
pii f = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int xx = f.first, yy = f.second;
xx += dx[i];
yy += dy[i];
if (xx < 1 || xx > n || yy < 1 || yy > n)
continue;
if (mp[xx][yy] != '0')
continue;
if (dis[xx][yy] > -1)
continue;
q.push({xx, yy});
dis[xx][yy] = dis[f.first][f.second] + 1;
if (dis[x2][y2] > 0)
return dis[x2][y2];
}
}
return -1;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; ++i) {
scanf("%s", mp[i] + 1);
}
cin >> x >> y >> x2 >> y2;
int result = bfs(x, y);
cout << result;
return 0;
}
by haogec123 @ 2023-09-10 22:21:30
你的输入在Linux环境下有问题\ 把输入改一下就好了
#include<iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> pii;
int dx[10] = {-1, 0, 1, 0};
int dy[10] = {0, 1, 0, -1};
int dis[1010][1010];
int n, x, y, x2, y2;
char mp[1010][1010];
queue<pii>q;
int bfs(int x, int y) {
memset(dis, -1, sizeof dis);
q.push({x, y});
dis[x][y] = 0;
while (!q.empty()) {
pii f = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int xx = f.first, yy = f.second;
xx += dx[i];
yy += dy[i];
if (xx < 1 || xx > n || yy < 1 || yy > n)
continue;
if (mp[xx][yy] != '0')
continue;
if (dis[xx][yy] > -1)
continue;
q.push({xx, yy});
dis[xx][yy] = dis[f.first][f.second] + 1;
if (dis[x2][y2] > 0)
return dis[x2][y2];
}
}
return -1;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
{
for(int j = 1;j <= n; j++)
{
cin>>mp[i][j];
}
}
cin >> x >> y >> x2 >> y2;
bfs(x, y);
cout << dis[x2][y2];
return 0;
}
by haogec123 @ 2023-09-10 22:22:15
@y6hz
by haogec123 @ 2023-09-10 22:29:25
求关