该题目来源于牛客网《剑指offer》专题。

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

Go语言实现:

func movingCount(threshold, rows, cols int) int {
//标记是否走过
//此处用数组无法指定长度,用切片操作下标越界,所以用map
flag := make(map[int]int)
return movingCountHandler(threshold, rows, cols, 0, 0, flag)
} func movingCountHandler(threshold, rows, cols, i, j int, flag map[int]int) int {
index := i*cols + j
count := 0
//不用循环,因为是从头开始
//i合法
//j合法
//此位置没走过
//坐标和小于threshold
if i >= 0 && i < rows && j >= 0 && j < cols && flag[index] == 0 && movingCountCheck(threshold, i, j) {
flag[index] = 1
//返回int,所以是加
count = 1 + movingCountHandler(threshold, rows, cols, i-1, j, flag) +
movingCountHandler(threshold, rows, cols, i+1, j, flag) +
movingCountHandler(threshold, rows, cols, i, j-1, flag) +
movingCountHandler(threshold, rows, cols, i, j+1, flag)
}
return count
} func movingCountCheck(threshold, i, j int) bool {
sum := 0
for i > 0 {
sum += i % 10 //取个位数
i = i / 10 //移除个位
}
for j > 0 {
sum += j % 10 //取个位数
j = j / 10 //移除个位
}
if sum > threshold {
return false
}
return true
}

最新文章

  1. dinic模板
  2. Scala 深入浅出实战经典 第60讲:Scala中隐式参数实战详解以及在Spark中的应用源码解析
  3. 使用Flask-Migrate进行管理数据库升级
  4. DataTable.Compute方法使用实例
  5. MySQL数据库备份和还原的常用命令小结
  6. sqlserver模糊查询【转】
  7. 【Xamarin开发 Android 系列 1】环境部署搭建
  8. fluentd结合kibana、elasticsearch实时搜索分析hadoop集群日志&lt;转&gt;
  9. codevs 1994 排队 排列组合+高精度
  10. 关于WPF中承载 ArcGIS控件。
  11. linux dd实现磁盘完整全盘镜像备份backup,恢复recover(restore)
  12. clientdataset&lt;----&gt;json
  13. ArrayBlockingQueue和LinkedBlockingQueue的区别
  14. centos 6.5 安装mongodb2.6
  15. 《java第一季之入门篇》的想法
  16. thymelead入门 git地址在文档最后
  17. POJ - 2057 The Lost House(树形DP+贪心)
  18. 20175320 2018-2019-2 《Java程序设计》第3周学习总结
  19. 网络编程初识和socket套接字
  20. try finally 处理方式

热门文章

  1. 2017CCPC杭州(ABCDJ)
  2. 密码 | 对称加密 - AES
  3. Java Collection集合中的iterator方法
  4. springcloud复习2
  5. 小白学Java:奇怪的RandomAccess
  6. 关于爬虫的日常复习(5)—— beautifulsoup库
  7. Linux系统终端session保持服务工具-Tmux
  8. azure 第一弹
  9. 【模板】普通平衡树(权值splay)
  10. DFS(深度优先搜索遍历有向图)-03-有向图-太平洋大西洋水流问题