The frozenset() is an inbuilt function is Python which takes an iterable object as input and makes them immutable. Since frozenset object are immutable they are mainly used as key in dictionary or elements of other sets
694 Number of Distinct Islands
尋找地圖中圖型pattern distinct的個數
dfs中紀錄原始座標,並在set中紀錄相對座標
defnumDistinctIslands(self,grid: List[List[int]]) ->int: self.m, self.n =len(grid),len(grid[0]) shapes =set()for i inrange(self.m):for j inrange(self.n):if grid[i][j] ==1: shape =set() self.helper(grid, shape, i, j, i, j) shape =frozenset(shape)if shape notin shapes: shapes.add(shape)returnlen(shapes)defhelper(self,grid,shape,i,j,i0,j0): grid[i][j] =0 shape.add((i-i0, j-j0))for dy, dx in ((0,1),(1,0), (0,-1), (-1,0)): y = i + dy x = j + dxifnot (0<= y < self.m and0<= x < self.n and grid[y][x] ==1):continue self.helper(grid, shape, y, x, i0, j0)
zfill
補0
s ='abc's =zfill(6)# s = '000abc'
frozenset()
將iterable 變成 hashable
694. Number of Distinct Islands
defnumDistinctIslands(self,grid: List[List[int]]) ->int: self.m, self.n =len(grid),len(grid[0]) shapes =set()for i inrange(self.m):for j inrange(self.n):if grid[i][j] ==1: shape =set() self.helper(grid, shape, i, j, i, j) shape =frozenset(shape)if shape notin shapes: shapes.add(shape)returnlen(shapes)defhelper(self,grid,shape,i,j,i0,j0): grid[i][j] =0 shape.add((i-i0, j-j0))for dy, dx in ((0,1),(1,0), (0,-1), (-1,0)): y = i + dy x = j + dxifnot (0<= y < self.m and0<= x < self.n and grid[y][x] ==1):continue self.helper(grid, shape, y, x, i0, j0)