|
| 1 | +class Solution(object): |
| 2 | + def numDistinctIslands(self, grid): |
| 3 | + """ |
| 4 | + :type grid: List[List[int]] |
| 5 | + :rtype: int |
| 6 | + """ |
| 7 | + distinctIlandSet = set() |
| 8 | + rows, cols = len(grid), len(grid[0]) |
| 9 | + for row in range(rows): |
| 10 | + for col in range(cols): |
| 11 | + if grid[row][col] == 1: |
| 12 | + currentIlanndPosition = [] |
| 13 | + self.numDistinctIslandsDFSHelper(grid, currentIlanndPosition, row, col, 0, 0) |
| 14 | + distinctIlandSet.add(tuple(currentIlanndPosition)) |
| 15 | + return len(distinctIlandSet) |
| 16 | + |
| 17 | + def numDistinctIslandsDFSHelper(self, grid, currentIlanndPosition, row, col, referrenceRowPos, referrenceColPos): |
| 18 | + grid[row][col] = -1 # marking this cell as visited |
| 19 | + currentIlanndPosition.append((referrenceRowPos, referrenceColPos)) |
| 20 | + neighbours = [(-1, 0), (0, 1), (1, 0), (0, -1)] |
| 21 | + for neighbour in neighbours: |
| 22 | + dr, dc = neighbour |
| 23 | + nextR, nextC = row + dr, col + dc |
| 24 | + nextReferrenceRowPos, nextReferrenceColPos = referrenceRowPos + dr, referrenceColPos + dc |
| 25 | + if 0 <= nextR < len(grid) and 0 <= nextC < len(grid[0]) and grid[nextR][nextC] == 1: |
| 26 | + self.numDistinctIslandsDFSHelper(grid, currentIlanndPosition, nextR, nextC, nextReferrenceRowPos, |
| 27 | + nextReferrenceColPos) |
| 28 | + |
0 commit comments