zoukankan      html  css  js  c++  java
  • 机器人的运动范围

    描述

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

    解析

    这个方格也可以看出一个 m*n 的矩阵。同样在这个矩阵中,除边界上的格子之外其他格子都有四个相邻的格子。

    机器人从坐标(0,0)开始移动。当它准备进入坐标为(i,j)的格子时,通过检查坐标的数位和来判断机器人是否能够进入。如果机器人能够进入坐标为(i,j)的格子,我们接着再

    判断它能否进入四个相邻的格子(i,j-1)、(i-1,j),(i,j+1) 和 (i+1,j)。

    使用深度优先搜索(Depth First Search,DFS)方法进行求解。回溯是深度优先搜索的一种特例,它在一次搜索过程中需要设置一些本次搜索过程的局部状态,并在本次搜索结束之后清除状态。

    代码

    public int movingCount(int threshold, int rows, int cols) {
            if (rows <= 0 || cols <= 0) {
                return 0;
            } else if (threshold < 0) {
                return 0;
            } else if (threshold == 0) {
                return 1;
            }
            boolean[][] visited = new boolean[rows][cols];
            return movingCountHelp(threshold, rows, cols, visited, 0, 0);
        }
        
        //计算以当前格子为出发点有多少可以走的格子
        public int movingCountHelp(int threshold, int rows, int cols, boolean[][] visited, int curRows, int curCols) {
            if (curRows < 0 || curRows >= rows || curCols < 0 || curCols >= cols || visited[curRows][curCols]
                || calc(curRows) + calc(curCols) > threshold) {
                return 0;
            }
            visited[curRows][curCols] = true;
            return movingCountHelp(threshold, rows, cols, visited, curRows - 1, curCols) + //
                    movingCountHelp(threshold, rows, cols, visited, curRows + 1, curCols) + //
                    movingCountHelp(threshold, rows, cols, visited, curRows, curCols - 1) +  //
                    movingCountHelp(threshold, rows, cols, visited, curRows, curCols + 1) +  //
                    1;//加上当前元素本身
        }
    
        //计算坐标的值,比如35,返回的值为8
        public int calc(int val) {
            int res = 0;
            while (val > 0) {
                res += val % 10;
                val = val / 10;
            }
            return res;
        }
  • 相关阅读:
    Tomcat配置
    Tomcat介绍和jbk安装
    nginx企业级优化
    linux 部署lnmp平台
    linux nginx服务
    linux rsync
    openssh远程连接及tcpwrappers防护
    linux 日志文件系统
    linux 解析文件系统原理
    linux 安全配置二
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/12563315.html
Copyright © 2011-2022 走看看