zoukankan      html  css  js  c++  java
  • 牛客(66)机器人的运动范围

    //    题目描述
    //    地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,
    //    每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。
    //    例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。
    //    但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
    
        public int movingCount(int threshold, int rows, int cols) {
            if (rows <= 0 || cols <= 0 || threshold <= 0) {
                return 0;
            }
    
            boolean[] isVisited = new boolean[rows * cols];
            int[] spots = {0};
    
            doHasPath(rows, cols, 0, 0, isVisited, spots, threshold);
            return spots[0];
        }
    
        public void doHasPath(int rows, int cols, int row, int col, boolean[] isVisited, int[] pathLength,
                              int threshold) {
    
            if (row >= 0 && col >= 0 && row < rows && col < cols && !isVisited[row * cols + col]) {
                if (toSum(row)+toSum(col)<=threshold){
                    pathLength[0]++;
                    isVisited[row * cols + col] = true;
                    doHasPath(rows, cols, row, col + 1, isVisited, pathLength, threshold);
                    doHasPath(rows, cols, row + 1, col, isVisited, pathLength, threshold);
                    doHasPath(rows, cols, row, col - 1, isVisited, pathLength, threshold);
                    doHasPath(rows, cols, row - 1, col, isVisited, pathLength, threshold);
                }
                isVisited[row * cols + col] = true;
            }
            return;
        }
    
        public static int toSum(int num){
            int sum=0;
            String sNum = ""+num;
            String[] chars = sNum.split("");
            for (int i=0;i<chars.length;i++){
                sum += new Integer(chars[i]);
            }
            return sum;
        }
  • 相关阅读:
    「SOL」工厂选址(BZOJ)
    「NOTE」数论小札
    Flask实现简单的群聊和单聊
    python基础总结
    基于Flask和百度AI实现与机器人对话
    django创建路径导航
    django中权限控制到按钮级别
    django中非菜单权限的归属
    MongoDB的增删改查
    jQuery于js的区别和联系
  • 原文地址:https://www.cnblogs.com/kaibing/p/9138940.html
Copyright © 2011-2022 走看看