zoukankan      html  css  js  c++  java
  • 剑指offer-回溯法-机器人的运动范围-python

    题目描述

    地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
     
    思路:设置一个计数器,统计能够达到的格子数。创建一个全为1的m行和n列的矩阵。然后递归遍历该矩阵,(
    tmpi = list(map(int, list(str(i))))
    tmpj = list(map(int, list(str(j))))
    )这两句将遍历的数字转化为个位数的列表,比如32 --> [3,2] 然后相加为
    sum(tmpi)+sum(tmpj)>k
    接着每遍历一次就将全为1的矩阵中的一个值置为0
     
    # -*- coding:utf-8 -*-
    class Solution:
        def __init__(self):
            self.count = 0
        def movingCount(self, threshold, rows, cols):
            # write code here
            arr = [[1 for i in range(rows)]for j in range(cols)]
            self.count_path(arr,0,0,threshold)
            return self.count
        def count_path(self,arr,i,j,k):
            if i<0 or j<0 or i>=len(arr) or  j>=len(arr[0]):
                return 
            tmpi = list(map(int, list(str(i))))
            tmpj = list(map(int, list(str(j))))
            if sum(tmpi)+sum(tmpj)>k or arr[i][j]!=1:
                return
            arr[i][j] = 0
            self.count+=1
            self.count_path(arr,i+1,j,k)
            self.count_path(arr,i-1,j,k)
            self.count_path(arr,i,j+1,k)
            self.count_path(arr,i,j-1,k)
  • 相关阅读:
    mmap文件修改内容的写回
    信号处理之物理信号和软件信号
    从printXX看tty设备(5)串口终端
    从printXX看tty设备(3)键盘输入处理
    LeetCode——Hamming Distance
    LeetCode——Add Strings
    计算树的高度和节点的个数
    LeetCode——Diameter of Binary Tree
    LeetCode——Number of Boomerangs
    九大排序算法总结
  • 原文地址:https://www.cnblogs.com/ansang/p/11873447.html
Copyright © 2011-2022 走看看