地上有一個 mm 行和 nn 列的方格,橫縱座標範圍分別是 0∼m−10∼m−1 和 0∼n−10∼n−1。
一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格。
但是不能進入行座標和列座標的數位之和大於 kk 的格子。
請問該機器人能夠達到多少個格子?
樣例1
輸入:k=7, m=4, n=5
輸出:20
樣例2
輸入:k=18, m=40, n=40
輸出:1484
解釋:當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。
但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。
注意:
0<=m<=50
0<=n<=50
0<=k<=100
class Solution {
public:
/*
*
* 在這裏我們要好好考慮一下一個問題:
* 這裏說的是數位之和 大於一個閾值,因此這裏的話我們需要對每個數字都進行一下相加的操作;
* */
int get_single_sum(int x){
int s=0;
while (x ) {
s+= x%10;
x = x/10;
}
return s;
}
int get_sum(pair<int,int> p){
return get_single_sum(p.first) + get_single_sum(p.second);
}
/*
* 以上兩個函數爲計算求和的函數
* */
int movingCount(int threshold, int rows, int cols)
{
int result =0; // 在這裏定義結果爲0
if (!rows || !cols) return 0; //判斷一下邊界條件;
vector<vector<bool>> grid(rows,vector<bool>(cols));// 定義一個數組來判斷一下有沒有被訪問過,每個位置只能被訪問一次
queue <pair<int,int>> que;
que.push(make_pair(0,0)); // 在這裏我們從左上角 0,0 點開始遍歷;
int dx[4] = {-1, 0,1,0}; // 定義四個方向
int dy[4] = {0,1,0,-1};
while (que.size()){
auto q = que.front();
que.pop();// 要記得能夠彈出來
if(get_sum(q) > threshold || grid[q.first][q.second] ==true) continue; // 如果要是大於threshold 或者大於邊界值的話需要接着進行;
result ++; // result +1;
grid[q.first][q.second] = true;// 把數據賦值爲 True
for(int i =0; i<4 ;i++){
int x = q.first + dx[i]; // 在這裏開始遍歷四個方向的數據
int y = q.second + dy[i];
if(x>=0 && x<rows && y>=0 && y<cols){ // 這裏要首先進行一下邊界條件的判斷 ,很重要在這裏;
que.push({x,y}); // 把數據存起來;
}
}
}
return result; // 返回結果;
}
};
// 加油加油 Try to make yourself more excellent...