题目
地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
示例 1:
1
2 输入:m = 2, n = 3, k = 1
输出:3示例 2:
1
2 输入:m = 3, n = 1, k = 0
输出:1提示:
1 <= n,m <= 100
0 <= k <= 20
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
每一步有多个选择,每个选择被某种条件限制,而目标是求满足条件的情况数量,这种情形适合使用回溯法解决,因为我们需要遍历所有可能路径(必要时剪枝)才可能得到答案。
由于要求最多能到达多少格子,因此重复进入格子无意义且浪费时间。
因此,从左上角开始 DFS ,维护最大可到达格子数量即可。
每到达一个节点,有以下几种选择:
- 该节点已经来过,计数不会增加,返回0
- 该节点没来过,继续寻找下一个节点
- 遍历完所有子节点后计数加一返回计数
1 | class Solution { |
- 时间复杂度$O(mn)$
- 空间复杂度$O(mn)$