JZ66 机器人的运动范围
my version
dfs
错误记录
- a = b = [x for x in range(n)] 会使a、b指向同一空间
- 由于机器人从[0,0]开始运动,因此只有向右和向下两个方向可以走
class Solution:
def dfs(self, i, j, thre, rows, cols):
# print(i,j)
if i<0 or i>=rows or j<0 or j>=cols or self.visit[i][j]:
# 超出边界/已访问过
return
row, col = i, j
i_sum = j_sum = 0
while row:
i_sum += row % 10
row = row // 10
while col:
j_sum += col % 10
col = col // 10
if i_sum+j_sum>thre:
# 不满足要求
return
self.visit[i][j] = 1
# print('visit',self.visit)
# 左下右上
# self.dfs(i, j-1, thre, rows, cols)
self.dfs(i+1, j, thre, rows, cols)
self.dfs(i, j+1, thre, rows, cols)
# self.dfs(i-1, j, thre, rows, cols)
def movingCount(self, threshold, rows, cols):
self.visit = [[0 for i in range(cols)] for i in range(rows)]
self.dfs(0, 0, threshold, rows, cols)
res = 0
for i in range(rows):
for j in range(cols):
res += self.visit[i][j]
return res
其他题解
bfs
from queue import Queue
class Solution:
def index_sum(self,i, j):
res = 0
while i:
res += i % 10
i = i // 10
while j:
res += j % 10
j = j // 10
return res
def movingCount(self, threshold, rows, cols):
q = Queue()
visit = [[0 for i in range(cols)] for i in range(rows)]
res = 0
if rows and cols:
q.put((0,0))
while not q.empty():
i,j = q.get()
if i<0 or i>=rows or j<0 or j>=cols or visit[i][j] or self.index_sum(i,j)>threshold:
continue
visit[i][j] = 1
res += 1
q.put((i, j+1))
q.put((i+1,j))
return res