JZ12-题解 | #机器人的运动范围#
机器人的运动范围
http://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8
题目描述
地上有一个 rows 行和 cols 列的方格。坐标从 [0,0] 到 [rows-1,cols-1] 。一个机器人从坐标 [0,0] 的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于 threshold 的格子。 例如,当 threshold 为 18 时,机器人能够进入方格 [35,37] ,因为 3+5+3+7 = 18。但是,它不能进入方格 [35,38] ,因为 3+5+3+8 = 19 。请问该机器人能够达到多少个格子?
题解:DFS遍历(不撞南墙不回头)
算法思路:
- 由于给出了矩阵入口,因此不需要寻找递归入口
- 需要辅助数组记录已经走过的路径。
- 需要一个求数位和的方法。
图示(来自牛客题霸)
代码
class Solution {
public:
//数位和函数
int getsum(int num){
int sum = 0;
while(num>0){
sum+=num%10;
num/=10;
}
return sum;
}
// dfs深度优先搜索
void dfs(int threshold,int& result, int row, int col,int rows, int cols,vector< vector<bool>> &visited){
//递归出口
if(row<0 || col<0 || row > rows-1 || col>cols-1)
return;
if(visited[row][col] == true || (getsum(row)+getsum(col))>threshold)
return;
//满足条件
visited[row][col] =true;
result++;
//分别递归
dfs(threshold,result,row+1,col,rows,cols,visited);
dfs(threshold,result,row-1,col,rows,cols,visited);
dfs(threshold,result,row,col+1,rows,cols,visited);
dfs(threshold,result,row,col-1,rows,cols,visited);
}
int movingCount(int threshold, int rows, int cols) {
int result = 0;
//辅助数组
vector< vector<bool> > visited(rows, vector<bool>(cols, false));
dfs(threshold,result,0,0,rows,cols,visited);
return result;
}
};
题解2:BFS广度优先遍历
算法思路: BFS/DFS : 两者目标都是遍历整个矩阵,不同点在于搜索顺序不同。DFS 是朝一个方向走到底,再回退,以此类推;BFS 则是按照“平推”的方式向前搜索。 BFS 实现: 通常利用队列实现广度优先遍历。

深信服公司福利 832人发布