994 腐烂的桃子
python
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
m,n=len(grid),len(grid[0])
fresh=0
q=[]
ans=0
for i,row in enumerate(grid):
for j,x in enumerate(row):
if x==1:fresh+=1
elif x==2:q.append((i,j))
while q and fresh:
tmp=q
q=[]
ans+=1
for x,y in tmp:
for i,j in (x-1,y),(x+1,y),(x,y-1),(x,y+1):
if 0<=i<m and 0<=j<n and grid[i][j]==1:
fresh-=1
q.append((i,j))
grid[i][j]=2
return -1 if fresh else ans
46 全排列
python
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
n=len(nums)
path=[0]*n
on_path=[False]*n
ans=[]
def dfs(i:int)->None:
if i==n:
ans.append(path.copy())
return
for j,on in enumerate(on_path):
if not on:
path[i]=nums[j]
on_path[j]=True
dfs(i+1)
on_path[j]=False
dfs(0)
return ans
78 子集
python
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
n=len(nums)
ans=[]
path=[]
def dfs(i:int)->None:
if i==n:
ans.append(path.copy())
return
dfs(i+1)
path.append(nums[i])
dfs(i+1)
path.pop()
dfs(0)
return ans