https://www.acwing.com/problem/content/1404/
这道题bfs一眼出
关键在于如何处理相同形状—哈希:对于相同形状的哈希处理方法有一个套路:
用一个vector存下所有组成当前形状的坐标,对所有坐标两两求欧几里得距离sqrt(double)
得到的双精度值就是哈希值,由于只有26个字母,所以在查找哈希值的时候遍历一遍即可
#include<bits/stdc++.h>
using namespace std;
#define N 510
typedef pair<int,int> pii;
#define x first
#define y second
const double eps=1e-8;
int n,m;
char g[N][N];
pii q[N*N];
int top;
double get_dist(pii A,pii B){
double dx=A.x-B.x,dy=A.y-B.y;
return sqrt(dx*dx+dy*dy);
}
double get_hash(){
double sum=0;
for(int i=0;i<top;i++)
for(int j=i+1;j<top;j++)
sum+=get_dist(q[i],q[j]);
return sum;
}
double get_id(double key){
static double hash[30];
static int id=0;
for(int i=0;i<id;i++)
if(fabs(hash[i]-key) < eps)
return i+'a';
hash[id++]=key;
return id-1+'a';
}
void dfs(int a,int b){
q[top++]={a,b};
g[a][b]='0';
for(int x=a-1;x<=a+1;x++)
for(int y=b-1;y<=b+1;y++){
if(x==a&&y==b) continue;
if(x>=0&&x<n&&y>=0&&y<m&&g[x][y]=='1')
dfs(x,y);
}
}
int main(){
cin >> m >> n;
for(int i=0;i<n;i++)
cin >> g[i];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(g[i][j]=='1'){
top=0;
dfs(i,j);
char ch=get_id(get_hash());
for(int k=0;k<top;k++)
g[q[k].x][q[k].y]=ch;
}
for(int i=0;i<n;i++)
cout << g[i] << endl;
return 0;
}