思路:首先dfs求得所有联通块,再搜索的同时把每个联通块的坐标都保存下来,然后把每个联通块处理一下–首先得到某个联通块的最小横坐标和纵坐标,然后让每个坐标去减去这个横坐标和纵坐标。相当于使得所有联通块都位于左上角了,然后再对坐标按照x和y排序就可以保证相同的联通块的所有坐标都一致。
后来想了一下,其实可以不排序,因为我们都是两层循环枚举一个点来进行扩展的,如果两个联通块(岛屿)形状一致,那么每次开始搜索的起点都是同一个位置,并且搜索时保证方向一直是(上下左右或则其他),只要保证方向不变那么就不需要排序。
AC代码
#include <stdio.h>
#include <string.h>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
#define inf 0x3f3f3f3f
const int maxn = 50+5;
int n, m;
char a[maxn][maxn];
bool vis[maxn][maxn];
int numOfIsland, numOfArea, numOfShape;
map<int, int> area;
struct pos{
int x, y;
pos(int x, int y):x(x), y(y){
}
bool operator < (const pos& p) const {
return x < p.x || (x == p.x && y < p.y);
}
};
struct pic{
vector<pos> arr;
void push(pos p) {
arr.push_back(p);
}
void deal() {
int Area = arr.size();
if(!area.count(Area)) {
area[Area] = 1;
numOfArea++;
}
int x = inf, y = inf;
for(int i = 0; i < arr.size(); i++) {
x = min(x, arr[i].x);
y = min(y, arr[i].y);
}
for(int i = 0; i < arr.size(); i++) {
arr[i].x -= x;
arr[i].y -= y;
}
sort(arr.begin(), arr.end());
}
}shape[maxn*maxn];
bool isSame(pic &a, pic &b) {
vector<pos> &p1 = a.arr, &p2 = b.arr;
if(p1.size() != p2.size()) {
return false;
}
for(int i = 0; i < p1.size(); i++) {
if(p1[i].x != p2[i].x || p1[i].y != p2[i].y) return false;
}
return true;
}
void init() {
memset(vis, 0, sizeof(vis));
numOfIsland = numOfArea = numOfShape = 0;
}
const int dx[] = {0,0,-1,1};
const int dy[] = {1,-1,0,0};
void dfs(int x, int y) {
shape[numOfIsland].push(pos(x, y));
vis[x][y] = 1;
for(int i = 0; i < 4; i++) {
int px = x + dx[i];
int py = y + dy[i];
if(px < 0 || px >= n || py < 0 || py >= m) continue;
if(a[px][py] == '#' && !vis[px][py]) {
vis[px][py] = 1;
dfs(px, py);
}
}
}
int main() {
init();
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++) {
scanf("%s", a[i]);
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(!vis[i][j] && a[i][j] == '#') {
dfs(i, j);
shape[numOfIsland].deal();
numOfIsland++;
}
}
}
for(int i = 0; i < numOfIsland; i++) {
bool ok = 1;
for(int j = 0; j < i; j++) {
if(isSame(shape[j], shape[i])) {
ok = 0;
break;
}
}
if(ok) numOfShape++;
}
printf("%d %d %d\n", numOfIsland, numOfArea, numOfShape);
return 0;
}
如有不当之处欢迎指出!