
思路:求2个联通所有点的曼哈顿距离的最小值
代码:
#include
#include
#include
#include
using namespace std; const int N = 55; #define x first #define y second typedef pair<int, int> PII; char g[N][N]; vector<PII> points[2]; int dx[4] = {
-1, 0, 1, 0}, dy[4] = {
0, 1, 0, -1}; int n,m; void dfs(int x,int y,int k){
g[x][y]='.'; points[k].push_back({
x,y}); for(int i=0;i<4;i++){
int a=x+dx[i]; int b=y+dy[i]; if(a<0||a>=n||b<0||b>=m||g[a][b]!='X') continue; dfs(a,b,k); } } int main() {
cin>>n>>m; for(int i=0;i<n;i++) cin>>g[i]; for(int i=0,k=0;i<n;i++) for(int j=0;j<m;j++) if(g[i][j]=='X'){
dfs(i,j,k); k++; } int res=1e8; for(auto& a:points[0]) for(auto& b:points[1]) res=min(res,abs(a.x-b.x)+abs(a.y-b.y)-1); cout<<res<<endl; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/217938.html原文链接:https://javaforall.net
