文献:https://blog.csdn.net/wesigj/article/details/108959219?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-1-108959219.pc_agg_new_rank&utm_term=stringstream+%E4%B8%ADssin&spm=1000.2123.3001.4430
题目:https://www.acwing.com/problem/content/description/730/
//输入很有特色
#include<iostream>
#include<cstring>
#include<queue>
#include<sstream>
using namespace std;
const int N = 15;
typedef pair<int,int>PII;
typedef pair<PII,int>PIII;
int dx[] = {0, 1, 0, -1}, dy[] = {1 , 0, -1, 0};
int g[N][N];
int n, m;
int bfs(){
int val = 0;
int start = 0;
int end = 0;
queue<PIII>q;
for(int i = 0; i < n; i ++ )
for(int j = 0; j < m; j ++ )
if(g[i][j] == 2) q.push({{i, j}, 0});
else if(g[i][j] == 1) start ++;
while(q.size()){
auto u = q.front();
q.pop();
PII uu = u.first;
int x = uu.first, y = uu.second, dist = u.second;
val = dist;
for(int i = 0; i < 4; i ++ ){
int a = dx[i] + x, b = dy[i] + y;
if(a >= 0 && b >= 0 && a < n && b < m && g[a][b] == 1){
q.push({{a, b}, dist + 1});
g[a][b] = 2;
end ++;
}
}
}
if(start == end) return val;
return -1;
}
int main(){
string line;
while(getline(cin, line)){
stringstream s(line);
int k = 0;
while(s >> g[n][k]) k ++;
m = k;
n ++;
}
cout<<bfs();
return 0;
}