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
    }
    
  • 相关阅读:
    面试精选:链表问题集锦
    经典排序算法总结与实现 ---python
    Python高级编程–正则表达式(习题)
    Python面试题汇总
    Python正则表达式
    Linux下的Libsvm使用历程录
    在 linux(ubuntu) 下 安装 LibSVM
    过拟合
    百度历年笔试面试150题
    MATLAB 的数据类型
  • 原文地址:https://www.cnblogs.com/dubinyang/p/12099428.html
Copyright © 2011-2022 走看看