题目来源
题目描述
给定一个 m × n的二维矩阵 grid ,使用或上、或下、或左、或右方向上相接的一组 1 代表一个岛屿。可以假定矩阵以外的区域都是海水。
如果两个岛屿之间形状相同,或者旋转(旋转角度仅可以为 90 、 180或 270 度)之后形状相同,或者镜像(可以沿上下或左右镜像)之后形状相同,就称这两个岛屿是相同的。
要求返回给定 grid 中包含的不同岛屿数量。
示例 1 :
- 输入: grid = [[1, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 1, 1]]
- 输出: 1
- 解释:如下图所示,将左上角的岛屿顺时针旋转 180 度之后将得到和右下角完全相同的岛屿。
- 示例 2
- 输入: grid = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1]]
- 输出: 1
题目解析
判断两个相同的岛屿:
- 如果两个岛屿能够通过平移、旋转、翻转操作能够重合,那么它们就是相同的
分析
- 假如给你几个长度相同的数组,是乱序的,怎么才能知道这些数组是否可以通过排序变成相同的数组呢?最简单的方法是对所有数组进行排序,排序后,如果相同,则属于同一类
- 同样的,如果我们能够找到一种方式,将所有属于同一类的岛屿形状变为唯一的结果,然后放到set中,最后集合中元素的个数就是不同岛屿的个数
思路
- 先找到每个单独的岛屿,将所有与其相连的位置都放到一个shape数组中
- 然后对所有的shape进行变化,目标变换成同一种岛屿形状的唯一标识
- 最后统计标识个数
怎么转换呢?
class Solution {
public:
int numDistinctIslands2(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
set<vector<pair<int, int>>> st;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j]) {
vector<pair<int, int>> shape;
helper(grid, i, j, shape);
st.insert(normalize(shape));
}
}
}
return st.size();
}
void helper(vector<vector<int>>& grid, int x, int y, vector<pair<int, int>>& shape) {
if (x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size()) return;
if (grid[x][y] == 0) return;
grid[x][y] = 0;
shape.push_back({x, y});
helper(grid, x + 1, y, shape);
helper(grid, x - 1, y, shape);
helper(grid, x, y + 1, shape);
helper(grid, x, y - 1, shape);
}
vector<pair<int, int>> normalize(vector<pair<int, int>>& shape) {
vector<vector<pair<int, int>>> shapes(8);
for (auto &a : shape) {
int x = a.first, y = a.second;
shapes[0].push_back({x, y});
shapes[1].push_back({x, -y});
shapes[2].push_back({-x, y});
shapes[3].push_back({-x, -y});
shapes[4].push_back({y, x});
shapes[5].push_back({y, -x});
shapes[6].push_back({-y, x});
shapes[7].push_back({-y, -x});
}
for (auto &a : shapes) {
sort(a.begin(), a.end());
for (int i = (int)shape.size() - 1; i >= 0; --i) {
a[i].first -= a[0].first;
a[i].second -= a[0].second;
}
}
sort(shapes.begin(), shapes.end());
return shapes[0];
}
};
怎么转换呢?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。