题目描述
Hearing that the latest fashion trend was cows with two spots on their hides, Farmer John has purchased an entire herd of two-spot cows. Unfortunately, fashion trends tend to change quickly, and the most popular current fashion is cows with only one spot!
FJ wants to make his herd more fashionable by painting each of his cows in such a way that merges their two spots into one. The hide of a cow is represented by an N by M (1 <= N,M <= 50) grid of characters like this:
Here, each ‘X’ denotes part of a spot. Two 'X’s belong to the same spot if they are vertically or horizontally adjacent (diagonally adjacent does not count), so the figure above has exactly two spots.
All of the cows in FJ’s herd have exactly two spots.
FJ wants to use as little paint as possible to merge the two spots into one. In the example above, he can do this by painting only three additional characters with 'X’s (the new characters are marked with '*'s below to make them easier to see).
Please help FJ determine the minimum number of new 'X’s he must paint in order to merge two spots into one large spot.
输入描述:
- Line 1: Two space-separated integers, N and M.
- Lines 2…1+N: Each line contains a length-M string of 'X’s and '.'s specifying one row of the cow hide pattern.
输出描述:
- Line 1: The minimum number of new 'X’s that must be added to the input pattern in order to obtain one single spot.
样例输入
样例输出
3
题目说明
解题思路
这道题的意思是牛皮上有两个X块,每个X块由若干个X符号组成,两个X块不相连,问你最少需要几个X字符能够将两个X块合成一个,然后矩阵由X和.组成,范围是1<=N,M<=50。
先进行深搜,找到两个X块中X的所有坐标,存储到vector数组中,然后通过循环坐标进行求最小距离(哈曼顿距离)
代码块
#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
char v[55][55];
vector<int>xp[3]; //存放坐标点
vector<int>yp[3];
int n,m;
void dfs(int x,int y,int t) //深搜找到一块X中的所有距离
{
if(x>n||x<1) return;
if(y>m||y<1) return;
if(v[x][y]=='X'){
xp[t].push_back(x);
yp[t].push_back(y);
v[x][y]='.'; //将X转成.避免重复查找
}
if(v[x-1][y]=='X'){
dfs(x-1,y,t);
}
if(v[x+1][y]=='X'){
dfs(x+1,y,t);
}
if(v[x][y+1]=='X'){
dfs(x,y+1,t);
}
if(v[x][y-1]=='X'){
dfs(x,y-1,t);
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>v[i][j];
}
}
int l=1;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(v[i][j]=='X'){
dfs(i,j,l++);
}
}
}
float t;
float minnum=200;
int minN = 2500;
int px1,py1,px2,py2;
for(int i=0;i<xp[1].size();i++){
for(int j=0;j<xp[2].size();j++){
px1=xp[1][i];
px2=xp[2][j];
py1=yp[1][i];
py2=yp[2][j];
minN = min(abs(px1-px2)+abs(py1-py2)-1,minN);
}
}
if(minN==2500)cout<<0;
else cout<<minN;
}
题目来源
链接:https://ac.nowcoder.com/acm/contest/7156/H
来源:牛客网