zoukankan      html  css  js  c++  java
  • Go语言实现:【剑指offer】机器人的运动范围

    该题目来源于牛客网《剑指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
    }
    
  • 相关阅读:
    poj3126--Prime Path(广搜)
    iOS中 imageNamed方法 非常多图片占用大量内存问题
    容器+AOP实现动态部署(四)
    SpringBoot整合redis哨兵主从服务
    LINUX安装REDIS集群
    软件安装
    如何优雅地用Redis实现分布式锁
    Redis面试总结
    OAuth2.0 知多少(好)
    一张图搞定OAuth2.0
  • 原文地址:https://www.cnblogs.com/dubinyang/p/12099428.html
Copyright © 2011-2022 走看看