C/C++面试题—机器人的运动范围【回溯法应用】
生活随笔
收集整理的這篇文章主要介紹了
C/C++面试题—机器人的运动范围【回溯法应用】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
地上有一個m行和n列的方格。一個機器人從坐標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行坐標和列坐標的數位之和大于k的格子。例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
解題思路
同樣是回溯法的應用,不過這次不是找路徑,而是找機器人能到達的位置的個數。只有到到一個合法的位置count計數+1,如果發現此路不通就回溯唄,繼續嘗試其他路徑!
解題代碼
#include <iostream> using namespace std; /* 題目描述:地上有一個m行和n列的方格。一個機器人從坐標0,0的格子開始移動, 每一次只能向左,右,上,下四個方向移動一格,但是不能進入行坐標和列坐標的數位之和大于k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。 但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?*/ class SolutionRobot { public:int movingCount(int threshold, int rows, int cols){if (threshold <= 0 || rows <= 0 || cols <= 0)return 0;int count = 0;bool *visited = new bool[rows*cols]{ false }; //訪問結點標識Count(0, rows, 0, cols, threshold, count,visited);delete[] visited;return count;}void Count(int row, int rows, int col, int cols, int threshold,int &count,bool* visited){if (row >= 0 && row < rows && col >= 0 && col < cols&& getSumNum(row) + getSumNum(col) <= threshold && !visited[row*cols + col]){count += 1; //該坐標位置滿足條件,能到達的格子數+1;visited[row*cols + col] = true;Count(row+1, rows, col, cols, threshold, count,visited);Count(row-1, rows, col, cols, threshold, count,visited);Count(row, rows, col+1, cols, threshold, count,visited);Count(row, rows, col-1, cols, threshold, count,visited);}}int getSumNum(int num) //計算數字位數之和{int sum = 0;while (num){sum += num % 10;num /= 10;}return sum;} };int main(int argc, char *argv[]) {SolutionRobot robot;/*1 1 1 11 1 1 11 1 1 11 1 1 1*///邊界值為6,->16int result = robot.movingCount(6, 4, 4);cout << result << endl;//邊界值為5,[3][3] 非法,->15result = robot.movingCount(5, 4, 4);cout << result << endl;//邊界值為4,[3][3] [3][2] [2][3]非法,->13result = robot.movingCount(4, 4, 4);cout << result << endl;return 0; }運行測試
總結
以上是生活随笔為你收集整理的C/C++面试题—机器人的运动范围【回溯法应用】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (三)表格型方法
- 下一篇: QTCreator2.8.0+Qt Op