剑指OFFER 机器人的运动范围
矩形搜索的变形,可以深搜,也可以广搜. 思维上没有什么难度,但是需要细心.
深搜代码
class Solution {
public:
int counter = 0;
vector<pair<int,int> > rotate_fac;
int m_threshold;
int m_rows;
int m_cols;
vector<vector<bool> > matrix;
bool check(int x,int y)
{
int sum = 0;
int xx = x;
int yy = y;
while (xx != 0) {
sum += xx % 10;
xx /= 10;
}
while (yy != 0) {
sum += yy % 10;
yy /= 10;
}
if(x>=0 && y>=0 && x<m_rows && y<m_cols && matrix[x][y]==false && sum <= m_threshold)return true;
else return false;
}
void recur(int x,int y)
{
matrix[x][y]=true;
counter++;
for(int i=0;i<4;i++)
{
if(check(x+rotate_fac[i].first,y+rotate_fac[i].second))
{
recur(x+rotate_fac[i].first,y+rotate_fac[i].second);
}
}
}
int movingCount(int threshold, int rows, int cols)
{
//handling special cases
if (rows == 0 || cols == 0 || threshold < 0)return 0;
//initialize
counter = 0;
m_threshold = threshold;
m_rows = rows;
m_cols = cols;
rotate_fac.push_back(pair<int,int>(0,1));
rotate_fac.push_back(pair<int,int>(1,0));
rotate_fac.push_back(pair<int,int>(0,-1));
rotate_fac.push_back(pair<int,int>(-1,0));
matrix.resize(rows);
for(int i=0;i<rows;i++)
{
matrix[i].resize(cols);
}
recur(0,0);
return counter;
}
};