题解 | #机器人的运动范围#
机器人的运动范围
http://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8
每次向右或者向下运动即可 使用回溯法 if中有flag判断是因为反正有格子重复计算 使用取模 除法 来实现位数相加
public class Solution {
int count = 0;
public int movingCount(int threshold, int rows, int cols) {
boolean[][] flag = new boolean[rows][cols];
dfs(threshold, rows, cols, 0,0,flag);
return count;
}
private void dfs(int threshold, int rows, int cols,int i,int j,boolean[][] flag){
if(i >= rows || j >= cols || flag[i][j] || sum(i)+sum(j) > threshold){
return;
}
flag[i][j] = true;
count++;
dfs(threshold, rows, cols, i+1,j,flag);
dfs(threshold, rows, cols, i,j+1,flag);
}
private int sum(int threshold){
int sum = 0;
while(threshold != 0){
sum += threshold%10;
threshold /= 10;
}
return sum;
}
}
剑指offer刷题记录 文章被收录于专栏
这个专栏主要记录算法刷题记录 希望对看到的人有所帮助
查看20道真题和解析