地上有一个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:
输入:m = 2, n = 3, k = 1 输出:3
示例 2:
输入:m = 3, n = 1, k = 0 输出:1
解题思路:
广度优先算法,使用递归暴力遍历数组。因为机器人是从(0,0)开始运动的,使用广度优先算法,只用到向下和向右便可以遍历到所有符合条件的。代码:
class Solution { public int movingCount(int m, int n, int k) { boolean[][] visited = new boolean[m][n]; //判断是否已经访问过了 int res = 0;//符合条件的个数 Queue<int[]> queue= new LinkedList<>(); queue.add(new int[] { 0, 0}); while(queue.size() > 0) { int[] x = queue.poll();//取出队头 int i = x[0], j = x[1]; if(i >= m || j >= n || k <count(i,j) || visited[i][j]) continue; visited[i][j] = true; res ++; queue.add(new int[] { i + 1, j}); queue.add(new int[] { i, j + 1}); } return res; } //数组各个位数之和 public int count(int i,int j){ int sum = 0; while(i != 0){ sum += i%10; i /= 10; } while(j != 0){ sum += j%10; j /= 10; } return sum; } }参考链接: https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/solution/mian-shi-ti-13-ji-qi-ren-de-yun-dong-fan-wei-dfs-b/ 题目来源: https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof
