声明:题目、程序来自《剑指offer》,注释、分析为自己写下备忘,侵删
递归(回溯)
题目:地上有一个m行n列的方格。一个机器人从座标((0, 0)的格子开始移动,它每次可以向左、右、上、下移动一格,但不能进入行座标和列座标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格(35; 37)}因为3十5+3+7=18。但它不进入方格(35, 38),因为3+5+3+8=19}请问该机器人能够到达多少个格子?分析:可以一个格子一个格子计算,但每行或每列上的格子与其相邻的格子座标有关系。不产生数位进位的情况下,右移一格子,数位之和加一。每列下移一个格子,数位之和加一。所以在数位之和为k的座标之上和之左的座标都可以到达。
再进一步,暂时想不出能快速解决的方法,那就还是用递归(回溯法)。
程序来自《剑指offer》
int movingCount(int threshold, int rows, int cols) { if(threshold < 0 || rows <= 0||cols<=0)//输入的总行列数是从一开始的。 return 0; bool *visited = new bool[rows*cols]; memset(visited, 0, rows*cols); itn count = movingCountCore(threshold, rows, cols, 0, 0, visited); delete[] visited; return count; } //递归调用自身,返回count值 int movingCountCore(int threshold, int rows, int cols, int row, int col, bool* visited) { int count = 0; if(check(threshold, rows, cols, row, col, visited)){ visited[row*cols +col] = true; count = 1 +movingCountCore(threshold, rows, cols, row, col-1, visited)+movingCountCore(threshold, rows, cols, row-1, col, visited) + movingCountCore(threshold, rows, cols, row, col+1, visited)+movingCountCore(threshold, rows, cols, row+1, col, visited); } return count; } //判断单独一个数字是否符合要求 bool check(int threshold, int rows, int cols, int row, int col, bool* visited) { if(row>=0&&row<rows&&col>=0 && col<cols &&getDigitSum(row)+getDigitSum(col)<=threshold && !visited[row*cols+col]) return true; return false; } //计算一个数的数位之和 int getDigitSum(int number) { int sum = 0; while(number >0){ sum+=number%10; number /= 10; } return sum; }