牛客网刷题之机器人的路径

来源:互联网 发布:哪个明星开了淘宝店铺 编辑:程序博客网 时间:2024/05/18 01:25

题目描述:

这里写图片描述

解题思路:

该题类似上一题,同样是使用回溯法来解决。所不同的是结束条件不一样而已。

题解:

 public int movingCount(int threshold, int rows, int cols) {        int tmp[][] = new int[rows][cols];        return moving(threshold, rows, cols, tmp, 0, 0);    }    private int moving(int threshold, int rows, int cols, int[][] tmp, int i,            int j) {        if (threshold <= 0 || i < 0 || i >= rows || j < 0 || j >= cols                || tmp[i][j] == 1 || (sum(i) + sum(j)) > threshold) {            return 0;        }        tmp[i][j] = 1;        return moving(threshold, rows, cols, tmp, i + 1, j)                + moving(threshold, rows, cols, tmp, i - 1, j)                + moving(threshold, rows, cols, tmp, i, j + 1)                + moving(threshold, rows, cols, tmp, i, j - 1)                + 1;    }    private int sum(int i) {        if (i == 0) {            return i;        }        int sum = 0;        while (i != 0) {            sum += i % 10;            i /= 10;        }        return sum;    }
0 0
原创粉丝点击