星空之夜
具体代码:
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#define x first
#define y second
#define N 110
#define esq 1e-6
using namespace std;
typedef pair<int,int> PII;
char g[N][N]; //地图
PII q[N*N]; //存放连通块
int top; //指向q数组
int h,w;
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 < h && y >= 0 && y < w && g[x][y] == '1')
dfs(x,y);
}
}
double get_dist(PII a,PII b)
{
double dx = a.x - b.x;
double 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 = 0;j < top;j ++)
sum += get_dist(q[i],q[j]);
return sum;
}
char get_id(double key)
{
static double hash[30];
static int id = 0;
for(int i = 0;i < id;i ++)
if(fabs(hash[i] - key) < esq)
return i + 'a';
hash[id++] = key;
return id - 1 + 'a';
}
int main()
{
cin>>w>>h;
for(int i = 0;i < h;i ++) cin>>g[i];
for(int i = 0;i < h;i ++)
for(int j = 0;j < w;j ++)
if(g[i][j] == '1')
{
top = 0;
dfs(i,j);
char c = get_id(get_hash());
for(int k = 0;k < top;k ++)
g[q[k].x][q[k].y] = c;
}
for(int i = 0;i < h;i ++) cout<<g[i]<<endl;
}