juggernaut_485 @ 2024-10-09 01:11:34
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII; //存坐标
const int N = 1010;
PII source, terminal;
int n,g[N][N]; //存地图
int dist[N][N]; //存从发点到该坐标的距离
queue <PII> q;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int bfs(PII s){
memset(dist,-1,sizeof dist); //将距离矩阵初始化为-1
dist[s.x][s.y] = 0; //发点距离设为0
q.push(s);
while(!q.empty()){
PII cur_cdn = q.front();
for(int i = 0; i < 4; i++){
int a = cur_cdn.x + dx[i], b = cur_cdn.y + dy[i];
if(a < 1 || a > n || b < 1 || b > n) continue;
if(g[a][b] == 1) continue;
if(dist[a][b] != -1) continue;
q.push({a,b});
dist[a][b] = dist[cur_cdn.x][cur_cdn.y] + 1;
}
q.pop();
}
return dist[terminal.x][terminal.y];
}
int main(){
//数据输入
cin >> n;
cin.ignore();
for (int i = 1; i <= n; i++) {
string line;
getline(cin, line);
// 将字符串中的每个字符转换为整数存储到二维数组中
for (int j = 1; j <= n; j++) {
g[i][j] = line[j-1] - '0'; // 将字符转换为整数
}
}
cin >> source.x >> source.y >> terminal.x >> terminal.y;
//开始BFS
int res = bfs(source);
cout << res << endl;
}
by summ1t @ 2024-10-09 06:38:18
输入的问题
cin.ignore()
改成
cin.ignore(1024,'\n')
具体可看这里