题目描述
分析
一个星群就对应一个连通块, 题目所求即将二维矩阵中相似的连通块用同一符号标记出来.
首先要找出矩阵中所有的连通块, 可以借助FloodFill算法
搜索出所有的连通块
接下来如何找到相似的连通块呢? 我们采用哈希
的方式
我们发现上图相似星群两点间的欧几里得距离 ( ( x 1 − x 2 ) 2 + ( y 1 − y 2 ) 2 ) (\sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}) ((x1−x2)2+(y1−y2)2)之和是相同的
我们便可以该距离之和作为哈希表的 k e y key key, 符号表示作为哈希表的 v a l u e value value
这样相似的星群就会被映射成同一个符号表示
从而得到答案
看不懂就参考Y总视频讲解
实现
#include <cstdio>
#include <iostream>
#include <map>
#include <cmath>
using namespace std;
const int N = 109;
const double eps = 1e-6;
int m, n;
int cnt; // 记录当前连通块中方格数量
int dx[] = {0,1,1,1,0,-1,-1,-1}, dy[] = {1,1,0,-1,-1,-1,0,1}; // 八方向连通,不是四方向
char w[N][N]; // 储存二维01矩阵
char ans[N][N]; // 输出最终的结果矩阵
pair<int, int> pos[N*N]; // 记录当前连通块各方格的坐标
double hashTable[30]; // 最多有26种星云
int index; // 记录当前已经出现过的字符种类的数量
bool check(int x, int y) // 判断当前位置是否合法
{
if(x < 0 || y < 0 || x >= n || y >= m) return false;
if(w[x][y] == '0') return false;
return true;
}
void dfs(int x, int y) // 搜索连通块
{
pos[cnt].first = x, pos[cnt].second = y, cnt++;
w[x][y] = '0'; // 标记一下代表已经搜过
for(int i = 0; i < 8; i++)
{
int nx = x + dx[i], ny = y + dy[i];
if(check(nx, ny)) dfs(nx, ny);
}
return;
}
double get_hash() // 计算当前连通块的哈希值, 即两点间的欧几里得距离之和
{
double sum = 0;
for(int i=0; i<cnt-1; i++)
{
for(int j=i+1; j<cnt; j++)
{
int x1 = pos[i].first, x2 = pos[j].first, y1 = pos[i].second, y2 = pos[j].second;
sum += sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
}
}
return sum;
}
char get_ch(double key) // 根据哈希函数的key找到对应的字符value
{
for(int i=0; i<index; i++)
{
if(fabs(key - hashTable[i]) <= eps) // 可能有误差
return 'a' + i;
}
hashTable[index++] = key;
return 'a' + index - 1;
}
int main()
{
cin >> m >> n;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cin >> w[i][j]; // debug: 题目输入是字符串
ans[i][j] = w[i][j];
}
}
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(w[i][j] == '0') continue;
cnt = 0; // 重新计数
dfs(i, j);
char c = get_ch(get_hash());
for(int i=0; i< cnt; i++)
{
int x = pos[i].first, y = pos[i].second;
ans[x][y] = c;
}
}
}
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cout << ans[i][j];
}
cout << endl;
}
return 0;
}