[Leetcode] 694. Number of Distinct Islands 解题报告

题目

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
00011
Given the above grid map, return  1 .

Example 2:

11011
10000
00001
11011
Given the above grid map, return  3 .

Notice that:
11
1
and
 1
11
are 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}};
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值