机器人走迷宫
在解题时应注意题目问的为可以到达的且行坐标和列坐标的位数之和不大于k的位置。所以必须使用搜索算法来解决问题。
代码:
class Solution {
public:
int get_sum(pair<int,int> p){
int s=0;
while(p.first)
{
s+=p.first%10;
p.first/=10;
}
while(p.second)
{
s+=p.second%10;
p.second/=10;
}
return s;
}
int movingCount(int threshold, int rows, int cols)
{
if(!rows||!cols)return 0;
queue<pair<int,int>>q;
vector<vector<bool>>st(rows,vector<bool>(cols,false));
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
int res=0;
q.push({0,0});
while(q.size())
{
auto t=q.front();
q.pop();
if(st[t.first][t.second]||get_sum(t)>threshold) continue;
res++;
st[t.first][t.second]=true;
for(int i=0;i<4;i++)
{
int x=t.first+dx[i],y=t.second+dy[i];
if(x>=0&&x<rows&&y>=0&&y<cols)q.push({x,y});
}
}
return res;
}
};
这篇博客探讨了一种使用搜索算法解决机器人在迷宫中行走的问题。重点在于理解如何确保行坐标和列坐标的位数之和不超过给定阈值。代码示例中展示了如何实现这一算法,包括定义求和函数、使用广度优先搜索(BFS)遍历可行位置,并更新已访问状态。最后,返回满足条件的可到达位置数量。
6760

被折叠的 条评论
为什么被折叠?



