测试用例存在BUG
机器人的运动范围
http://www.nowcoder.com/questionTerminal/6e5207314b5241fb83f2329e89fdecc8
使用方法1可以通过测试用例,方法2也可以通过测试用例,但是对于movingCount(8,6,20),两种方法得到的答案不一样,使用方法2(BFS)得到的结果是正确的39,方法1(遍历)得到的结果是72.测试用例不严谨
方法1. 使用暴力遍历,并且在行数只有一行或者列数只有一行是返回可以到达的格子数。这个解法可以通过所有测试用例,但是本方法对于我自己测试的用例得到错误的结果。可见上面加黑体部分
class Solution {
public:
int convert2sum(int num)
{
int ans=0;
while(num>0)
{
ans+=num%10;
num=num/10;
}
return ans;
}
int movingCount(int threshold, int rows, int cols)
{
int count=0;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(convert2sum(i)+convert2sum(j)<=threshold)
{
count++;
}
else if(cols==1||rows==1)
{
return count;
}
}
}
return count;
}
};方法2. 使用BFS
class Solution {
public:
int convert2sum(int num)
{
int ans = 0;
while (num>0)
{
ans += num % 10;
num = num / 10;
}
return ans;
}
int movingCount(int threshold, int rows, int cols)
{
if (threshold<0)
{
return 0;
}
int count = 0;
queue<pair<int, int>>q;
vector<vector<bool>>visited(rows, vector<bool>(cols, false));
visited[0][0] = true;
q.push({ 0,0 });
while (!q.empty())
{
pair<int, int>p = q.front();
q.pop();
int i = p.first;
int j = p.second;
count++;
if (i - 1 >= 0 && visited[i - 1][j] == false && convert2sum(i - 1) + convert2sum(j) <= threshold)
{
visited[i - 1][j] = true;
q.push({ i - 1,j });
}
if (i + 1<rows&&visited[i + 1][j] == false && convert2sum(i + 1) + convert2sum(j) <= threshold)
{
visited[i + 1][j] = true;
q.push({ i + 1,j });
}
if (j - 1 >= 0 && visited[i][j - 1] == false && convert2sum(i) + convert2sum(j - 1) <= threshold)
{
visited[i][j - 1] = true;
q.push({ i,j - 1 });
}
if (j + 1<cols&&visited[i][j + 1] == false && convert2sum(i) + convert2sum(j + 1) <= threshold)
{
visited[i][j + 1] = true;
q.push({ i,j + 1 });
}
}
return count;
}
};