题解 | #机器人的运动范围#

机器人的运动范围

https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8

import java.util.*;
public class Solution {
    public int movingCount(int threshold, int rows, int cols) {

        //
        int flag[][] = new int[rows][cols];
        int count = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                flag[i][j] = 0;
            }
        }
        haveCount(threshold, 0, 0, flag);
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                count += flag[i][j];
            }
        }
        return count;
    }
    public int haveCount(int threshold, int rows, int cols, int flag[][]) {
        if (rows > flag.length - 1 || cols > flag[0].length - 1 || rows < 0 ||
                cols < 0) {//下标超出数组范围
            return 0;
        }
        if (flag[rows][cols] == 1) { //表示该节点已经被访问过
            return 0;
        }
        if (getSum(rows) + getSum(cols) > threshold) {
            return 0;
        }
        flag[rows][cols] = 1;
        haveCount(threshold, rows, cols + 1, flag);
        haveCount(threshold, rows + 1, cols, flag);
        haveCount(threshold, rows, cols - 1, flag);
        haveCount(threshold, rows - 1, cols, flag);
        return 1;
    }
    public  int getSum(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n = n / 10;
        }
        return sum;
    }
}

全部评论

相关推荐

白火同学:大二有这水平很牛了,可以适当对关键信息加粗一点,比如关键技术、性能指标之类的。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务