当前位置:   article > 正文

AcWing 2060. 奶牛选美 (DFS 枚举)

AcWing 2060. 奶牛选美 (DFS 枚举)

2060. 奶牛选美 - AcWing题库

yxc代码AcWing 2060. 奶牛选美 - AcWing

题意:上下左右连通的点X被看做一个连通块,现在有两个连通块,求两个连通块的最小曼哈顿距离

P(xP,yP),Q(xQ,yQ)两点间的曼哈顿距离的计算方法:
            Manhattan(P,Q)=|xP−xQ|+|yP−yQ|

 思路:dfs找出两个连通块包含的点,然后分别枚举两个连通块各点  到另外连通块点的曼哈顿距离,取最小值

  1. #include<bits/stdc++.h>
  2. #define x first
  3. #define y second
  4. using namespace std;
  5. typedef pair<int,int> PII;
  6. const int N=55;
  7. int n,m;
  8. char g[N][N];
  9. vector<PII> points[2];
  10. int dx[4]={-1,0,0,1},dy[4]={0,1,-1,0};
  11. void dfs(int x,int y,vector<PII>& ps)
  12. {
  13. g[x][y]='.';
  14. ps.push_back({x,y});
  15. for(int i=0;i<4;i++)
  16. {
  17. int a=x+dx[i],b=y+dy[i];
  18. if(a>=0&&a<n&&b>=0&&b<m&&g[a][b]=='X')
  19. {
  20. dfs(a,b,ps);
  21. }
  22. }
  23. }
  24. int main()
  25. {
  26. cin>>n>>m;
  27. for(int i=0;i<n;i++) cin>>g[i];
  28. for(int i=0,k=0;i<n;i++)
  29. {
  30. for(int j=0;j<m;j++)
  31. {
  32. if(g[i][j]=='X')
  33. {
  34. dfs(i,j,points[k++]);
  35. }
  36. }
  37. }
  38. int res=1e8;
  39. for(auto&a:points[0])
  40. for(auto&b:points[1])
  41. res=min(res,abs(a.x-b.x)+abs(a.y-b.y)-1);
  42. cout<<res<<endl;
  43. return 0;
  44. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/415847
推荐阅读
相关标签
  

闽ICP备14008679号