zoukankan      html  css  js  c++  java
  • 剑指offer:机器人的运动范围(回溯法DFS)

    题目描述

      地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
      

    解题思路

      采用回溯法,通过深度优先遍历

    代码 

    public class Solution {
        public static int m;//迷宫的行数
        public static int n;//迷宫的列数
        public static int k;//不能进入行坐标和列坐标的位数之和大于k的格子
        public static boolean[][] flag;//用于标记该格子是否被走过
        
        public static int movingCount(int threshold, int rows, int cols){
            m = rows;
            n = cols;
            k = threshold;
            flag = new boolean[m][n];
            return dfs(0,0);//从坐标0,0的格子开始移动
        }
         /**
         * 采用回溯法,通过深度优先遍历
         * @param i 行号
         * @param j    列号
         * @return 从当前位置(i,j)出发最多能到达多少个格子
         */
        public static int dfs(int i, int j){
            /**如果行列越界||如果行和列的各位之和大于给定的数||如果该点已经访问过了,则直接返回 */
            if(i<0||i>=m||j<0||j>=n||sumdigits(i)+sumdigits(j)>k||flag[i][j]){
                return 0;
            }
            flag[i][j] = true;/**表示访问过了**/
            /**如果可以进入本格子,则判断与它相邻的四个格子*/
            return dfs(i+1,j)+dfs(i-1,j)+dfs(i,j-1)+dfs(i,j+1)+1;
        }
        /**求出一个数各个位置上的和*/
        public static int sumdigits(int threshold){
            int sum  = 0;
            while(threshold!=0){
                sum += threshold%10;
                threshold /=10;
            }
            return sum;
        }
        
    }
  • 相关阅读:
    排序_简单选择排序
    排序_冒泡排序
    笔试_阿里_逆波兰表达式
    刷题_牛客_大整数排序
    刷题_牛客_字符串编码
    刷题_thinkinginjava_吸血鬼数字
    刷题_牛客_超级素数幂
    刷题_LeetCode_Two Sum
    刷题_LeetCode_Reverse Integer
    854. Floyd求最短路(模板)
  • 原文地址:https://www.cnblogs.com/haimishasha/p/11307444.html
Copyright © 2011-2022 走看看