【66】機器人的運動範圍 時間限制:1秒 空間限制:32768K 回溯法
題目描述
地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,
每一次只能向左,右,上,下四個方向移動一格,
但是不能進入行座標和列座標的數位之和大於k的格子。
例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。
但是,它不能進入方格(35,38),因為3+5+3+8 = 19。
請問該機器人能夠達到多少個格子。
牛客網題目連結點擊這裡 VS2010代碼:
// Source: http://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8?tpId=13&tqId=11219&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking// Author: Yang Qiang// Date : 2016-8-15#include<iostream>using namespace std;///思路分析://1.機器人路徑範圍是一個連通地區。因此要把可達範圍都記錄一下。//2.要對每個位置的四個方向均作出判斷。class Solution { /********位和控制函數函數****************/ //超出控制範圍,返回0,否則返回1; bool SumOfBit(int threshold1,int curRow, int curCol) { int SumBit=0; while(curRow) { SumBit=SumBit+curRow%10; curRow=curRow/10; } while(curCol) { SumBit=SumBit+curCol%10; curCol=curCol/10; } return SumBit>threshold1?0:1; } /**********路徑尋找函數**********/ //輸入:控制閾值,矩陣行列;當前行列,標誌矩陣 //輸出改點是否能繼續前進 void FindPath(int threshold1, int rows1, int cols1, int curRow, int curCol, int* flag) { //邊界控制:超出邊界,該方向無法繼續 if(curRow<0 || curCol<0 || curRow>rows1-1 || curCol>cols1-1) return; //位和控制:位和不滿足,該方向無法繼續 if(!SumOfBit(threshold1,curRow,curCol) ) return; //標誌位控制:已走過的路徑不再繼續 if(flag[curRow*cols1+curCol]==1) return; //當前位置通過監測,更新標誌位,繼續搜尋 flag[curRow*cols1+curCol]=1; FindPath( threshold1,rows1,cols1, curRow-1, curCol, flag); //向上 FindPath( threshold1,rows1,cols1, curRow, curCol+1, flag); //向右 FindPath( threshold1,rows1,cols1, curRow+1, curCol, flag); //向下 FindPath( threshold1,rows1,cols1, curRow, curCol-1, flag); //向左 //bool hasPath=0; //hasPath=FindPath( threshold1,rows1,cols1, curRow-1, curCol, flag) //向上 // || FindPath( threshold1,rows1,cols1, curRow, curCol+1, flag) //向右 // || FindPath( threshold1,rows1,cols1, curRow+1, curCol, flag) //向下 // || FindPath( threshold1,rows1,cols1, curRow, curCol-1, flag); //向左 //如果該位置的四周都不行 /*if(!hasPath) return*/ }public: int movingCount(int threshold, int rows, int cols) { //非法情況定義 if(threshold<0 || rows<1 || cols<1) return 0; //定義一個標誌矩陣,記錄走過的路徑。 int* Flag=new int[rows*cols]; for(int i=0; i<rows*cols; i++) Flag[i]=0; //初始化一次標誌位 //尋找路徑,並標記 FindPath( threshold,rows,cols, 0, 0, Flag); //遍曆矩陣,找出標記的個數。 int reachedNum=0; for(int i=0; i<rows*cols; i++) { if(Flag[i]==1) reachedNum++; //初始化一次標誌位 } return reachedNum; }};int main(){ Solution s1; cout<<s1.movingCount(5,4,4)<<endl;}
牛客網通關圖片:
另附(劍指offer)66道通關卡片: