LeetCode Solutions

694. Number of Distinct Islands

Time: $O(mn)$

Space: $O(mn)$

			

class Solution {
 public:
  int numDistinctIslands(vector<vector<int>>& grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    set<vector<pair<int, int>>> islands;  // All different islands
    vector<vector<bool>> seen(m, vector<bool>(n));

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        vector<pair<int, int>> island;
        dfs(grid, i, j, i, j, seen, island);
        if (!island.empty())
          islands.insert(island);
      }

    return islands.size();
  }

 private:
  void dfs(const vector<vector<int>>& grid, int i, int j, int i0, int j0,
           vector<vector<bool>>& seen, vector<pair<int, int>>& island) {
    if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size())
      return;
    if (grid[i][j] == 0 || seen[i][j])
      return;

    seen[i][j] = true;
    island.emplace_back(i - i0, j - j0);

    dfs(grid, i + 1, j, i0, j0, seen, island);
    dfs(grid, i - 1, j, i0, j0, seen, island);
    dfs(grid, i, j + 1, i0, j0, seen, island);
    dfs(grid, i, j - 1, i0, j0, seen, island);
  }
};
			

class Solution {
  public int numDistinctIslands(int[][] grid) {
    final int m = grid.length;
    final int n = grid[0].length;
    Set<List<Pair<Integer, Integer>>> islands = new HashSet<>(); // All different islands
    boolean[][] seen = new boolean[m][n];

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        List<Pair<Integer, Integer>> island = new ArrayList<>();
        dfs(grid, i, j, i, j, seen, island);
        if (!island.isEmpty())
          islands.add(island);
      }

    return islands.size();
  }

  private void dfs(int[][] grid, int i, int j, int i0, int j0, boolean[][] seen,
                   List<Pair<Integer, Integer>> island) {
    if (i < 0 || i == grid.length || j < 0 || j == grid[0].length)
      return;
    if (grid[i][j] == 0 || seen[i][j])
      return;

    seen[i][j] = true;
    island.add(new Pair<>(i - i0, j - j0));

    dfs(grid, i + 1, j, i0, j0, seen, island);
    dfs(grid, i - 1, j, i0, j0, seen, island);
    dfs(grid, i, j + 1, i0, j0, seen, island);
    dfs(grid, i, j - 1, i0, j0, seen, island);
  }
}
			

class Solution:
  def numDistinctIslands(self, grid: List[List[int]]) -> int:
    seen = set()

    def dfs(i: int, j: int, i0: int, j0: int):
      if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]):
        return
      if grid[i][j] == 0 or (i, j) in seen:
        return

      seen.add((i, j))
      island.append((i - i0, j - j0))
      dfs(i + 1, j, i0, j0)
      dfs(i - 1, j, i0, j0)
      dfs(i, j + 1, i0, j0)
      dfs(i, j - 1, i0, j0)

    islands = set()  # All different islands

    for i in range(len(grid)):
      for j in range(len(grid[0])):
        island = []
        dfs(i, j, i, j)
        if island:
          islands.add(frozenset(island))

    return len(islands)