聲明:題目、程序來自《劍指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; }