博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
机器人的运动范围
阅读量:6990 次
发布时间:2019-06-27

本文共 1375 字,大约阅读时间需要 4 分钟。

题目描述

地上有一个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 int movingCount(int threshold, int rows, int cols){    if(rows<1 || cols <1 || threshold<0){        return 0;    }    //判断是否访问过    boolean[] isVisited=new boolean[rows * cols];    return getCount(threshold,rows,cols,0,0,isVisited);     }public int getCount(int threshold,int rows,int cols,int row,int col,boolean[] isVisited){    int count = 0;    if(check(threshold,rows,cols,row,col,isVisited)){        isVisited[row*cols+col]=true;        count=1+getCount(threshold,rows,cols,row-1,col,isVisited)+getCount(threshold,rows,cols,row+1,col,isVisited)+            getCount(threshold,rows,cols,row,col-1,isVisited)+getCount(threshold,rows,cols,row,col+1,isVisited);    }    return count;}//检查public boolean check(int threshold,int rows,int cols,int row,int col,boolean[] isVisited){    if(row>=0 && row< rows && col>=0 && col < cols && !isVisited[row*cols+col]){        if((getNumberSum(row)+getNumberSum(col))<=threshold){            return true;        }    }    return false;     }public int getNumberSum(int num){    int sum=0;    while(num>0){        sum+=num%10;        num=num/10;    }    return sum;}}

转载于:https://www.cnblogs.com/rookieJW/p/9322043.html

你可能感兴趣的文章
[转] sql 删除表数据的drop、truncate和delete用法
查看>>
python基础——切片
查看>>
设计模式之适配器模式
查看>>
Oracle 字符集的查看和修改
查看>>
pwd, cd, ls, touch, mkdir, rmdir, rm
查看>>
ArcGIS Engine开发之地图基本操作(2)
查看>>
Redis性能问题排查解决手册(七)
查看>>
如何在Windows系统上用抓包软件Wireshark截获iPhone等网络通讯数据
查看>>
[LintCode] LRU Cache 缓存器
查看>>
计算机名、主机名、用户账户名与NetBIOS名有什么区别
查看>>
[Angular 2] BYPASSING PROVIDERS IN ANGULAR 2
查看>>
Django基础-过滤器
查看>>
javascript命名规范
查看>>
Git 生命周期
查看>>
最短路径Floyd算法【图文详解】
查看>>
Linux 静态链接库和动态连接库
查看>>
基于DDD的现代ASP.NET开发框架--ABP系列之1、ABP总体介绍
查看>>
Hadoop生态圈-Oozie部署实战
查看>>
.NET Core中基类可以反射子类的成员
查看>>
iOS开发之OC与swift开发混编教程,代理的相互调用,block的实现。OC调用Swift中的代理, OC调用Swift中的Block 闭包...
查看>>