轉載于《劍指Offer》
題目
地上有一個m行和n列的方格。一個機器人從坐标0,0的格子開始移動,每一次隻能向左,右,上,下四個方向移動一格,但是不能進入行坐标和列坐标的數位之和大于k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
代碼
int getDigitSum(int number){
int sum = ;
while (number > ){
sum += number % ;
number /= ;
}
return sum;
}
bool check(int threshold, int rows, int cols, int row, int col, bool* visited){
if (row >= && row<rows && col >= && col < cols && getDigitSum(row) + getDigitSum(col) <= threshold && !visited[row*cols+col])
return true;
return false;
}
int movingCountCore(int threshold, int rows, int cols, int row, int col, bool* visited){
int count = ;
if (check(threshold, rows, cols, row, col, visited)){
visited[row*cols + col] = true;
count = + movingCountCore(threshold, rows, cols, row - , col, visited) + movingCountCore(threshold, rows, cols, row, col - , visited) + movingCountCore(threshold, rows, cols, row + , col, visited) + movingCountCore(threshold, rows, cols, row, col + , visited);
}
return count;
}
int movingCount(int threshold, int rows, int cols){
bool *visited = new bool[rows*cols];
memset(visited, , rows*cols);
int count = movingCountCore(threshold, rows, cols, , , visited);
delete[] visited;
return count;
}//回溯法