劍指Offer上的原題
地上有一個m行n列的方格,從座標 [0,0] 到座標 [m-1,n-1] 。一個機器人從座標 [0, 0] 的格子開始移動,它每次可以向左、右、上、下移動一格(不能移動到方格外),也不能進入行座標和列座標的數位之和大於k的格子。例如,當k爲18時,機器人能夠進入方格 [35, 37] ,因爲3+5+3+7=18。但它不能進入方格 [35, 38],因爲3+5+3+8=19。請問該機器人能夠到達多少個格子?
示例1:
輸入:m = 2, n = 3, k = 1
輸出:3
示例2:
輸入:m = 3, n = 1, k = 0
輸出:1
方法一:BFS
話不多說直接BFS開搜。
class Solution {
public:
int movingCount(int m, int n, int k) {
queue<pair<int, int> > bfs;
bfs.push(make_pair(0, 0));
int reached[m][n];
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
reached[i][j] = 0;
}
}
int addition_x[] = {0, 0, -1, 1};
int addition_y[] = {1, -1, 0, 0};
int countCell = 0;
while (!bfs.empty()){
int currentX = bfs.front().first, currentY = bfs.front().second;
bfs.pop();
if (reached[currentX][currentY] == 0){
reached[currentX][currentY] = 1;
countCell++;
// cout << countCell << endl;
}
else if (reached[currentX][currentY] == 1){
continue;
}
for (int i = 0; i < 4; i++){
int newX = currentX + addition_x[i], newY = currentY + addition_y[i];
if (newX < 0 || newX >= m || newY < 0 || newY >= n || reached[newX][newY] == 1){
continue;
}
else{
int digitSum = 0, tempX = newX, tempY = newY;
for (; newX; digitSum += newX % 10, newX /= 10);
for (; newY; digitSum += newY % 10, newY /= 10);
if (digitSum <= k) bfs.push(make_pair(tempX, tempY));
}
}
}
return countCell;
}
};
方法二:回溯法
class Solution {
public:
int movingCount(int m, int n, int k) {
if (k < 0 || m <= 0 || n <= 0) return 0;
bool visited[m*n];
for (int i = 0; i < m*n; i++) {
visited[i] = false;
}
int count = this->movingCountCore(k, m, n, 0, 0, visited);
return count;
}
// 回溯算法核心
int movingCountCore(int k, int m, int n, int startRow, int startCol, bool* visited) {
int count = 0;
if (check(k, m, n, startRow, startCol, visited)) {
visited[startRow*n+startCol] = true;
count = 1 + movingCountCore(k, m, n, startRow - 1, startCol, visited) + \
movingCountCore(k, m, n, startRow, startCol - 1, visited) + \
movingCountCore(k, m, n, startRow + 1, startCol, visited) + \
movingCountCore(k, m, n, startRow, startCol + 1, visited);
}
return count;
}
// check函數用來判斷一個機器人能否進入一個方格
bool check(int k, int rows, int cols, int row, int col, bool* visited) {
if (row >= 0 && row < rows && col >= 0 && col < cols && getDigitSum(row) + getDigitSum(col) <= k && !visited[row*cols+col]) {
return true;
}
return false;
}
// 得到一個數字的數位和
int getDigitSum(int number) {
int digitSum = 0;
for (; number; digitSum += number % 10, number /= 10);
return digitSum;
}
};