1 class Solution(object): 2 def __init__(self): 3 self.cons = 0 4 self.S = list() 5 6 def dfs(self,m,n,v,A): 7 while len(self.S) > 0: 8 cur = self.S.pop(-1) 9 cur_x = cur[0] 10 cur_y = cur[1] 11 v[cur_x][cur_y] = 1 12 self.cons += 1 13 14 if cur_x > 0 and A[cur_x-1][cur_y]==1 and v[cur_x-1][cur_y] == 0: 15 self.S.append([cur_x-1,cur_y]) 16 self.dfs(m,n,v,A) 17 18 if cur_x < m - 1 and A[cur_x + 1][cur_y]==1 and v[cur_x + 1][cur_y]== 0: 19 self.S.append([cur_x+1,cur_y]) 20 self.dfs(m,n,v,A) 21 22 if cur_y > 0 and A[cur_x][cur_y-1]==1 and v[cur_x][cur_y-1]==0: 23 self.S.append([cur_x,cur_y-1]) 24 self.dfs(m,n,v,A) 25 26 if cur_y < n - 1 and A[cur_x][cur_y+1]==1 and v[cur_x][cur_y+1]==0: 27 self.S.append([cur_x,cur_y+1]) 28 self.dfs(m,n,v,A) 29 30 31 return 0 32 33 def numEnclaves(self, A: 'List[List[int]]') -> int: 34 row = len(A) 35 coloum = len(A[0]) 36 visited = [[0 for c in range(coloum)] for r in range(row)] 37 sumsA = 0 38 for i in range(row): 39 for j in range(coloum): 40 sumsA += A[i][j] 41 if sumsA == 0: 42 return 0 43 44 #first row and last row 45 for i in [0,row-1]: 46 for j in range(coloum): 47 if A[i][j] == 0 or visited[i][j] == 1: 48 continue 49 else: 50 self.S.append([i,j]) 51 self.dfs(row,coloum,visited,A) 52 53 #first coloum and last coloum 54 for j in [0,coloum - 1]: 55 for i in range(row): 56 if A[i][j] == 0 or visited[i][j] == 1: 57 continue 58 else: 59 self.S.append([i,j]) 60 self.dfs(row,coloum,visited,A) 61 62 return sumsA - self.cons
解决思路是使用DFS,为了提高效率,只扫描外边框(第一行,最后一行,第一列,最后一列),并使用一个数组记录是否已经访问。