题目:
Given a non-empty 2D array grid
of 0's and 1's, an island is a group of 1
's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Count the number of distinct islands. An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other.
Example 1:
11000 11000 00011 00011Given the above grid map, return
1
.
Example 2:
11011 10000 00001 11011Given the above grid map, return
3
.
Notice that:
11 1and
1 11are considered different island shapes, because we do not consider reflection / rotation.
Note: The length of each dimension in the given grid
does not exceed 50.
思路:
标准的DFS题目:采用深度优先搜索算法识别出来每一个孤岛,然后将它们放在一个集合中,这样形状相同的孤岛就被合并了。问题是如何存储孤岛的形状呢?看到网上一个巧妙的方法,就是将孤岛的形状存储成为一个二维数组vector<vector<int>> island,其中里面的每一个vector<int>就是其相对于该岛的左上角的位置island[0]的偏移量。
我们在这里采用了set的方法来存储孤岛,但是采用unordered_set应该也是可以的。
代码:
class Solution {
public:
int numDistinctIslands(vector<vector<int>>& grid) {
int row_num = grid.size(), col_num = grid[0].size();
set<vector<vector<int>>> islands;
for (int r = 0; r < row_num; ++r) {
for (int c = 0; c < col_num; ++c) {
if (grid[r][c] > 0) {
// we use vector<vector<int>> to represent the shape of a island
vector<vector<int>> island;
DFS(r, c, r, c, grid, row_num, col_num, island);
islands.insert(island);
}
}
}
return islands.size();
}
private:
void DFS(int sr, int sc, int r, int c, vector<vector<int>> &grid,
int row_num, int col_num, vector<vector<int>> &island) {
if (r < 0 || r >= row_num || c < 0 || c >= col_num ||grid[r][c] <= 0) {
return;
}
island.push_back({r - sr, c - sc});
grid[r][c] = -1;
for (int d = 0; d < 4; ++d) {
DFS(sr, sc, r + delta[d][0], c + delta[d][1], grid,
row_num, col_num, island);
}
}
int delta[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
};