题解 | #机器人的运动范围#
机器人的运动范围
http://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8
# -*- coding:utf-8 -*- def canGet(matrix,i,j,rows,cols,thre): res=int(i/10)+i%10+int(j/10)+j%10 if i<0&nbs***bsp;i>=rows&nbs***bsp;j<0&nbs***bsp;j>=cols: return False elif res>thre: return False if matrix[i*cols+j]: return False return True def dfs(matrix,i,j,rows,cols,dirs,thre): cnt=0 if(canGet(matrix,i,j,rows,cols,thre)): matrix[i*cols+j]=True cnt=1+dfs(matrix, i-1, j, rows, cols, dirs, thre)+dfs(matrix, i+1, j, rows, cols, dirs, thre)+dfs(matrix, i, j-1, rows, cols, dirs, thre)+dfs(matrix, i, j+1, rows, cols, dirs, thre) return cnt class Solution: def movingCount(self, threshold, rows, cols): if threshold<0: return 0 if threshold==0: return 1 dirs=[[0,-1],[0,1],[-1,0],[1,0]] # cnt=0 matrixh=[False]*(rows*cols) # for x in range(rows): # for y in range(cols): # matrixh.append(0.0) # for m in range(rows): # for n in range(cols): # matrix[m][n]=0 i,j=0,0 cnt=dfs(matrixh, i, j, rows, cols, dirs,threshold) return cnt # write code here
用DFS:
注意记录访问状态的matrix。我前几次一直用二维数组来存,但不知为何一直报错:TypeError: 'bool' object is not subscriptable。换成一维数组后就过了....