C/C++面试题—机器人的运动范围【回溯法应用】
生活随笔
收集整理的這篇文章主要介紹了
C/C++面试题—机器人的运动范围【回溯法应用】
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目描述
地上有一個(gè)m行和n列的方格。一個(gè)機(jī)器人從坐標(biāo)0,0的格子開始移動(dòng),每一次只能向左,右,上,下四個(gè)方向移動(dòng)一格,但是不能進(jìn)入行坐標(biāo)和列坐標(biāo)的數(shù)位之和大于k的格子。例如,當(dāng)k為18時(shí),機(jī)器人能夠進(jìn)入方格(35,37),因?yàn)?+5+3+7 = 18。但是,它不能進(jìn)入方格(35,38),因?yàn)?+5+3+8 = 19。請(qǐng)問該機(jī)器人能夠達(dá)到多少個(gè)格子?
解題思路
同樣是回溯法的應(yīng)用,不過這次不是找路徑,而是找機(jī)器人能到達(dá)的位置的個(gè)數(shù)。只有到到一個(gè)合法的位置count計(jì)數(shù)+1,如果發(fā)現(xiàn)此路不通就回溯唄,繼續(xù)嘗試其他路徑!
解題代碼
#include <iostream> using namespace std; /* 題目描述:地上有一個(gè)m行和n列的方格。一個(gè)機(jī)器人從坐標(biāo)0,0的格子開始移動(dòng), 每一次只能向左,右,上,下四個(gè)方向移動(dòng)一格,但是不能進(jìn)入行坐標(biāo)和列坐標(biāo)的數(shù)位之和大于k的格子。 例如,當(dāng)k為18時(shí),機(jī)器人能夠進(jìn)入方格(35,37),因?yàn)?+5+3+7 = 18。 但是,它不能進(jìn)入方格(35,38),因?yàn)?+5+3+8 = 19。請(qǐng)問該機(jī)器人能夠達(dá)到多少個(gè)格子?*/ 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 }; //訪問結(jié)點(diǎn)標(biāo)識(shí)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; //該坐標(biāo)位置滿足條件,能到達(dá)的格子數(shù)+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) //計(jì)算數(shù)字位數(shù)之和{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; }運(yùn)行測(cè)試
總結(jié)
以上是生活随笔為你收集整理的C/C++面试题—机器人的运动范围【回溯法应用】的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (三)表格型方法
- 下一篇: QTCreator2.8.0+Qt Op