机器人的运动范围
2015-10-02 17:50
302 查看
题目描述
地上有一个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的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路:回溯法
class Solution { public: int getDig(int i) { int sum=0; while(i!=0) { sum+=i%10; i=i/10; } return sum; } bool checkMoving(int threshold,int rows,int cols,int i,int j,bool visited[]) { if(i>=0 && i<rows && j>=0 && j<cols && !visited[i*cols+j] && getDig(i)+getDig(j)<=threshold) { return true; } return false; } int movingCountCore(int threshold,int rows,int cols,int i,int j,bool visited[]) { int count=0; if(checkMoving(threshold,rows,cols,i,j,visited)) { visited[i*cols+j]=true; count=1+movingCountCore(threshold,rows,cols,i-1,j,visited) +movingCountCore(threshold,rows,cols,i+1,j,visited) +movingCountCore(threshold,rows,cols,i,j-1,visited) +movingCountCore(threshold,rows,cols,i,j+1,visited); } return count; } int movingCount(int threshold, int rows, int cols) { int count = 0; bool *visited = new bool[rows*cols]; memset(visited,0,rows*cols); count=movingCountCore(threshold,rows,cols,0,0,visited); delete[] visited; return count; } };
相关文章推荐
- 顺序串
- 深刻理解void,void*和sizeof关键字
- 【创龙TMS320C6748开发板试用】+几种基本的程序下载和烧写办法总结
- 黑马程序员----C语言学习笔记之学习总结《通讯录》程序实现
- hdoj-2014 青年歌手大奖赛_评委会打分【sort排序||冒泡排序】
- JavaWeb中3种中文乱码问题的解决方法
- Hadoop Streaming 得到mapreduce_map_input_file中遇到的问题的版本号
- BZOJ 1013: [JSOI2008]球形空间产生器sphere 高斯消元
- Hadoop2.7.1——64位源码编译
- 好难
- OC中点运算符和->的用法区别(转载)
- 【创龙TMS320C6748开发板试用】+DEBUG模式下的led控制
- hdu5302 构造
- github学习 之 在github 上获取源码
- DM6437平台开发-----程序烧写3
- c++工厂模式
- 08.08_面向对象(代码块的概述和分类)
- NCL介绍与安装 记一次不平凡的经历!
- swift 中switch 的新用法
- 【创龙TMS320C6748开发板试用】+开箱照及CCS环境简介