- 题目:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
- 思路:
- 从起始点开始走,通过DFS走到所有能走的地方
- 走过的地方要标记为1,不能走的标记为0
- 启发或者坑:
- dfs之后是否要返回到初始状态,这个题目是不用的*-*
- 代码:
class Solution { public: int rowsV; int colsV; vector<vector<int>> mark; int k; int nums; int movingCount(int threshold, int rows, int cols) { rowsV = rows; colsV = cols; for (int i = 0; i < rows; i++) { vector<int> onerow; for (int j = 0; j < cols; j++) { onerow.push_back(-1); } mark.push_back(onerow); } k = threshold; nums = 0; dfs(0,0); return nums; } void dfs(int start_x, int start_y) { //从这个位置startx,starty,向四面八方走,找str[strIndex] //cout << "start dfs, start_x: " << start_x << " start_y: " << start_y << " strIndex: " << strIndex << endl; /*for (int i = 0; i < mark.size(); i++) { cout << mark[i] << " "; } cout << endl;*/ if ((getSum(start_x) + getSum(start_y)) > k) { mark[start_x][start_y] = 0; //第一次忘记写return,不能粗心呀hh return; } else { nums++; mark[start_x][start_y] = 1; } int xChange[4] = {0, 0, 1, -1}; int yChange[4] = {1, -1, 0, 0}; for (int i = 0; i < 4; i++) { int x = start_x + xChange[i]; int y = start_y + yChange[i]; if (x < 0 || x >= rowsV) continue; if (y < 0 || y >= colsV) continue; if (mark[x][y] == 1 || mark[x][y] == 0) continue; dfs(x, y); } } int getSum(int num) { int sum = 0; while(num) { sum += num % 10; num = num/10; } return sum; } };
来源:CSDN
作者:快乐划水程序猿
链接:https://blog.csdn.net/Alexia23/article/details/104092976