タイトル説明
接地グリッドと、m行n列。0,0グリッド座標からロボットが移動し、毎回四方セルを上下、左右が、グリッドの行および列の座標を入力することができないだけではビットkの数の合計よりも大きいです。kが18である場合、例えば、ロボットが3 + 3 + 5 + 7 = 18から、ボックス(35、37)を入力することができます。3 + 3 + 5 + 8 = 19しかし、それは、ボックス(35、38)を入力することができません。ロボットは、格子の数に到達することができるだろうか?
思考
(0,0)から歩行を開始し、現在の位置をマークすることで成功するたびにステップが真である、その後、4つの方向に現在の位置から探ります。探索は、現在のノードが到達可能な基準であるか否かを判定する:
1)行列の現在のノードと、
2)現在のノードがアクセスされていない;
3)を満たし、現在のノードの制限制限。
到達できた場合は、カウント、対応するフラグが真であるマーク++
コード
class Solution {
public:
int count= 0;
int movingCount(int threshold, int rows, int cols)
{
if(threshold < 1 || rows < 1 || cols <1)
return 0;
bool *flag=new bool[rows*cols];
memset(flag,false,rows*cols);
move_on(threshold,rows,cols,0,0,flag);
return count;
}
void move_on(int threshold, int rows, int cols, int P_x, int P_y, bool* flag)
{
int index = P_x * cols + P_y;
int condition = cal(P_x,P_y);
if(P_x < 0 || P_x > rows-1 || P_y < 0 || P_y > cols-1 || condition > threshold || flag[index] == true)
return;
flag[index] = true;
count++;
move_on(threshold,rows,cols,P_x+1,P_y,flag);
move_on(threshold,rows,cols,P_x,P_y+1,flag);
move_on(threshold,rows,cols,P_x-1,P_y,flag);
move_on(threshold,rows,cols,P_x,P_y-1,flag);
return;
}
int cal(int x, int y)
{
int res = 0;
string s_x,s_y,s;
s_x = to_string(x);
s_y = to_string(y);
s = s_x + s_y;
for(int i = 0; i < s.size();i++)
{
res = res + s[i]-'0';
}
return res;
}
};