[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> island,其中里面的每一个vector就是其相对于该岛的左上角的位置island[0]的偏移量。

我们在这里采用了set的方法来存储孤岛,但是采用unordered_set应该也是可以的。

代码

class Solution {
public:
    int numDistinctIslands(vector>& grid) {
        int row_num = grid.size(), col_num = grid[0].size();
        set>> 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> to represent the shape of a island
                    vector> 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> &grid, 
             int row_num, int col_num, vector> &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}};
};

你可能感兴趣的:(IT公司面试习题)